Extracting from a list
Daniel Dittmar
daniel at dittmar.net
Wed Apr 10 17:42:46 EDT 2002
Joel Bender wrote:
> I would like to process the elements of a list that match a condition,
> then remove them. I'll use integers in my example, but my list items
> are actually objects.
[...]
> I'd rather not scan the list twice, particularly if there's nothing to
> do. I'd rather not build another double-linked list.
>
> Is there something like this?
>
> >>> for item in lst:
> ... if (item < 5):
> ... print item
> ... del lst[ xxxx ]
>
> But the "trick" is figuring out what xxxx should be. Using lst.remove()
> would work if the internals used "is" and not "is equal to" and the
> removal didn't modify the list where it would break the loop somehow.
Using .remove () is similar to scanning the list, so it doesn't buy you anything in terms of performance.
How about:
for i in xrange (len (lst) - 1, -1, -1):
item = lst [i]
if item < 5:
print item
del lst [i]
This makes it possible to delete items from the list as the access is
back to front.
Daniel
More information about the Python-list
mailing list