Extracting from a list
Cliff Wells
logiplexsoftware at earthlink.net
Wed Apr 10 17:46:00 EDT 2002
On Wed, 10 Apr 2002 16:35:10 -0400
Joel Bender wrote:
> 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.
How about:
lst = [3, 2, 5, 1, 0, 7, 4, 8, 6, 9]
for item in lst:
if item < 5:
print item
lst = [i for i in lst if i >= 5]
This way you only process the list twice and don't need a redundant copy. If
you are really concerned about processing the list the second time when there's
nothing to be done, you could use a flag:
lst = [3, 2, 5, 1, 0, 7, 4, 8, 6, 9]
flag = 0
for item in lst:
if item < 5:
print item
flag = 1
if flag:
lst = [i for i in lst if i >= 5]
--
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308 (800) 735-0555 x308
More information about the Python-list
mailing list