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
Post a Comment