Deleting workspaces from a group

Interesting behaviour here which may have changed a bit recently. What’s supposed to happen?

# tidy up a temporary WorkspaceGroup, for example a loaded run taken in period mode
for w in wg:

This deletes MyWorkspace_1, MyWorkspace_3 etc and then fails trying to delete “None”.

The nearly equivalent code

for i in range(N):
    w= wg[i]

deletes 1,3 etc and then throws an exception that the index into the workspace group is out of range (which is more obvious why it’s wrong).
A correct solution is of course

for w in list(wg):

or just DeleteWorkspaces(wg).

Also is it intended that deleting the last member of a workspace group automatically deletes the group itself in a tidy manner? It does seem to disappear from the ADS.

I put your 3 ways into one script (which doesn’t run in its entirety, but each section will run):

from mantid.simpleapi import *
N = 5

'''A Deletes Odd Indices - Property "WORKSPACE" is not set to a valid value'''
for i in range(N):
    CreateSampleWorkspace(OutputWorkspace = 'wsa_{}'.format(i+1))
wgA = GroupWorkspaces(GlobExpression= 'wsa_?')

for w in wgA:            

'''B Deletes Odd Indices - IndexError: index out of range'''
for i in range(N):
    CreateSampleWorkspace(OutputWorkspace = 'wsb_{}'.format(i+1))

wgB = GroupWorkspaces(GlobExpression= 'wsb_?')

for i in range(N):        
    w= wgB[i]

'''C This way works'''
for i in range(N):
    CreateSampleWorkspace(OutputWorkspace = 'wsc_{}'.format(i+1))
wgC = GroupWorkspaces(GlobExpression= 'wsc_?')

for w in list(wgC):

In A and B, Python is deleting the first workspace index, then looking for the second, but it has shuffled to being the first and so the third gets deleted. In this way it ends up looking for indices outside its range!

In C it works correctly as the list of the workspace names to delete is fixed and so it can’t go wrong.

This is a useful thing to be aware of! As it relates to Python iteration I’m not sure that a change within Mantid would be appropriate. This behavior works the same in 4.2 and the Nightly (even though they are different Python versions) as far as I can tell.

Yes deleting the final workspace from a group also deletes the group as it would be annoying to have an empty group lying around.

Thanks. There’s no need to change Mantid, but perhaps add a bit to the documentation to clarify that a WorkspaceGroup is a sort of iterator in this context and (as elsewhere in Python) iterating over a group while adding or removing items is a bad idea.
As for deleting, the converse is that overwriting a WorkspaceGroup with a smaller group leaves the excess members orphaned at the top level of the ADS. But DeleteWorkspace iterates over the group members and tidies up.

I’ve created a pull request to reflect this in the Documentation: Edit WorkspaceGroup docs by DanielMurphy22 · Pull Request #27844 · mantidproject/mantid · GitHub