Extracting from a list

Bengt Richter bokr at oz.net
Wed Apr 10 18:10:15 EDT 2002


On Wed, 10 Apr 2002 16:35:10 -0400, Joel Bender <jjb5 at cornell.edu> 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.
>
You could do something like:
 >>> def prck(i):
 ...    if i>=5 : return 1
 ...    print i
 ...    return 0
 ...
 >>> lst  = [3, 2, 5, 1, 0, 7, 4, 8, 6, 9]
 >>> lst = [i for i in lst if prck(i)]
 3
 2
 1
 0
 4
 >>> lst
 [5, 7, 8, 6, 9]

Regards,
Bengt Richter



More information about the Python-list mailing list