>>> l = list(range(10))
>>> def f(l,d=False):
... for i in l:
... if d:
... l.remove(i)
... else:
... yield i
...
>>> list(f(l))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(f(l,d=True))
[]
>>> l
[1, 3, 5, 7, 9]
>>>
This example is not good Python, one should never modify a list while iterating it. There is a number of good SO posts about this, an example can be found here.
Make a deepcopy of the list:
from copy import deepcopy
def f(_list, remove_condition=False):
_ = deepcopy(_list)
for i in _:
if remove_condition:
_.remove(i)
else:
yield iOr change the remove flag around and do this:
def f(_list, do_not_remove_condition=True):
for i in _list:
if do_not_remove_condition:
yield i
else:
yieldWe can make that even shorter:
def f(_list, do_not_remove_condition=True):
for i in _list:
yield i if do_not_remove_condition else NoneAlso note that in this case we will get a None value for each element that is removed.
And finally, unless we really need a generator, why not a simple list comprehension:
new_l = [i for i in l if not remove_condition]I used a bool in the examples for simplicity, but remove_condition could be a function that validates each element of the list.