Extracting from a list

Bengt Richter bokr at oz.net
Wed Apr 10 23:25:44 EDT 2002


On Wed, 10 Apr 2002 18:13:02 -0600, Fernando =?ISO-8859-1?Q?P=E9rez?= <fperez528 at yahoo.com> wrote:

>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).
>
You might repack this way (it feels C-ish though ;-):

 >>> lst = [3, 2, 5, 1, 0, 7, 4, 8, 6, 9]
 >>> i=0
 >>> for j in xrange(len(lst)):
 ...     if lst[j]<5:
 ...         print lst[j]
 ...     else:
 ...         lst[i] = lst[j]
 ...         i += 1
 ...
 3
 2
 1
 0
 4
 >>> lst[i:]=[]
 >>> lst
 [5, 7, 8, 6, 9]

I'm not sure if the slice assignment is done in place,
but I think it could be.


Regards,
Bengt Richter



More information about the Python-list mailing list