Extracting from a list

Fernando Pérez fperez528 at yahoo.com
Wed Apr 10 20:13:02 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.
> 
> 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 don't know if it's 'right', but the following seems natural to me:

In [36]: def flt(x):
   ....:   if x<5:
   ....:     print x
   ....:     return 0
   ....:   else:
   ....:     return 1
   ....:

In [37]: lst
Out[37]:
[3, 2, 5, 1, 0, 7, 4, 8, 6, 9]

In [38]: filter(flt,lst)
3
2
1
0
4
Out[38]:
[5, 7, 8, 6, 9]

You can define the flt() function to suit your taste, add parameters to it, 
etc.

It's single pass, goes in the right order and returns the cleaned list. The 
only problem it has is that it generates a secondary list instead of 
modifying the existing one in-place. You're the only one who knows if that's 
a problem or not (it basically depends on the size of your lists and if you 
can afford the extra copy, even if just temporarily).

Cheers,

f.



More information about the Python-list mailing list