[Tutor] list iteration [iteration and mutation?]

Alan Gauld alan.gauld at blueyonder.co.uk
Tue May 4 17:01:49 EDT 2004

> Often, it's simplest to just iterate over a reversed range, such as
> l = <some kind of list we want to remove from>
>for i in range(len(l)-1, -1, -1):
>    if we_want_to_remove(l[i]):
>        del l[i]

I haven't seen it mentioned yet but list comprehensions can often
be used for this kind of task. Re-working Magnus' generic code:

L = [some kind of list we want to remove from]
L = [ item for item in L if not we_want_to_remove(item)]

In other words create a new list containing those items we
don't want to remove. It's even fairly readable! By reversing
the logic of we_want_to_remove() so that it represents
we_want_to_keep(), it becomes the even more readable

L = [item for item in L if we_want_to_keep(item)]


Alan G.

More information about the Tutor mailing list