I have a set myset
, and I have a function which iterates over it to perform some operation on its items and this operation ultimately deletes the item from the set.
Obviously, I cannot do it while still iterating over the original set. I can, however, do this:
mylist = list(myset)
for item in mylist:
# do sth
Is there any better way?
Let's return all even numbers while modifying current set.
Will return
If there is opportunity use always use
lambda
it will make your life easier.First, using a set, as Zero Piraeus told us, you can
I added a print method giving these outputs
If you want to stick to your choice for a list, i suggest you deep copy the list using a list comprehension, and loop over the copy, while removing items from original list. In my example, i make length of original list decrease at each loop.
gives
This ought to work:
Or, if you need to remove items conditionally:
Another way could be :
"Obviously, I cannot do it while still iterating over the original set."
I'm not sure that's true... I was expecting "concurrency" errors when I tried it but don't appear to have got any. For the record the code I'm using looks like this:
("member" is a better choice of variable name for sets; "element" for lists)
Ah... just seen the comment by kindall under Zero P's answer: obviously kindall is an expert where I am a bumbler, but I'll post my answer anyway just to draw attention to the point...
NB Zero P regards kindall's assertion that this is OK with hostility... but given that sets are, by design, unordered, I think we can conclude that concurrency errors should (and do? in Python?) crop up only when deleting from an ordered collection (i.e. list - and even then you could use a reverse index countdown to avoid the problem).
It would therefore appear that aversion to deletion-while-iterating is a matter of superstition and/or hangovers from bad experiences from poorly implemented structures in other languages.
Final thought: sets and iterations don't really go together terribly well: since a set is unordered you could only ever be iterating in random fashion over a subset of all members (specifically the subset 'all' or 'itself'!). Sets are optimised for equality tests and duplicate removal, and this reflects their intended use.
So an equivalent bit of code to the above (the ideal solution?) is: