python - delete items from a set while iterating over it -


i have set myset, , have function iterates on perform operation on items , operation deletes item set.

obviously, cannot while still iterating on original set. can, however, this:

mylist = list(myset) item in mylist:     # sth 

is there better way?

first, using set, 0 piraeus told us, can

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

i added print method giving these outputs

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

if want stick choice list, suggest deep copy list using list comprehension, , loop on copy, while removing items original list. in example, make length of original list decrease @ each loop.

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

gives

>>>  [3, 4, 5, 6] [4, 5, 6] [5, 6] [6] [] 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -