Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete items from a set while iterating over it

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?

like image 528
skyork Avatar asked May 14 '13 19:05

skyork


People also ask

Can you remove from a set while iterating?

Since we can't modify a set while iterating over it, we can create a duplicate set and remove elements that satisfy the condition from the original set by iterating over the duplicate set.

How do you remove something from a list while iterating?

If you want to delete elements from a list while iterating, use a while-loop so you can alter the current index and end index after each deletion.

How can we remove specific item from set?

Python Set remove() MethodThe remove() method removes the specified element from the set. This method is different from the discard() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.


1 Answers

First, using a set, as Zero Piraeus told us, you can

myset = set([3,4,5,6,2]) while myset:     myset.pop()     print(myset) 

I added a print method giving these outputs

>>>  set([3, 4, 5, 6]) set([4, 5, 6]) set([5, 6]) set([6]) set([]) 

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.

l = list(myset) l_copy = [x for x in l] for k in l_copy:     l = l[1:]     print(l) 

gives

>>>  [3, 4, 5, 6] [4, 5, 6] [5, 6] [6] [] 
like image 165
kiriloff Avatar answered Oct 01 '22 08:10

kiriloff