Reputation: 31491
Consider:
fooList = [1, 2, 3, 4] # Ints for example only, in real application using objects
for foo in fooList:
if fooChecker(foo):
remove_this_foo_from_list
How is the specific foo
to be removed from the list? Note that I'm using ints for example only, in the real application there is a list of arbitrary objects.
Thanks.
Upvotes: 1
Views: 147
Reputation: 251021
Iterate over a shallow copy of the list.
As you can't modify a list while iterating over so you need to iterate over a shallow copy of the list.
fooList = [1, 2, 3, 4]
for foo in fooList[:]: #equivalent to list(fooList), but much faster
if fooChecker(foo):
fooList.remove(foo)
Upvotes: 8
Reputation: 89027
Generally, you just don't want to do this. Instead, construct a new list instead. Most of the time, this is done with a list comprehension:
fooListFiltered = [foo for foo in fooList if not fooChecker(foo)]
Alternatively, a generator expression (my video linked above covers generator expressions as well as list comprehensions) or filter()
(note that in 2.x, filter()
is not lazy - use a generator expression or itertools.ifilter()
instead) might be more appropriate (for example, a large file that is too big to be read into memory wouldn't work this way, but would with a generator expression).
If you need to actually modify the list (rare, but can be the case on occasion), then you can assign back:
fooList[:] = fooListFiltered
Upvotes: 8
Reputation: 21985
Use filter
:
newList = list(filter(fooChecker, fooList))
or
newItems = filter(fooChecker, fooList))
for item in newItems:
print item # or print(item) for python 3.x
http://docs.python.org/2/library/functions.html#filter
Upvotes: -1