Extracting from a list
Joel Bender
jjb5 at cornell.edu
Wed Apr 10 16:35:10 EDT 2002
Hi,
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.
What's the "right" way to do this? For example:
>>> lst = [3, 2, 5, 1, 0, 7, 4, 8, 6, 9]
>>> dothese = [i for i in lst if i < 5]
>>> lst = [i for i in lst if i >= 5]
>>> for item in dothese:
... print item
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.
I could rebuild the list for things that should not be processed:
>>> newlst = []
>>> for item in lst:
... if (item < 5):
... print item
... else
... newlst.append(item)
>>> lst = newlst
But these seems like a lot of work when there's nothing in the list to
process.
Joel
More information about the Python-list
mailing list