Extracting from a list

Philip Swartzleonard starx at pacbell.net
Wed Apr 10 17:48:07 EDT 2002


Joel Bender || Wed 10 Apr 2002 01:35:10p:

> 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.

Two approaches come to mind, both using while instead (Because we need 
to use the number instead of just the item):

i = 0
while i < len(list)
    	if list[i] < 5:
    	    	print list[i]
    	    	del list[i]
    	i += 1

and

i = 0
used = []
length = len(list)
while i < length
    	if list[i] < 5:
    	    	print list[i]
    	    	used.append(i)
    	i += 1
for x in used
    	del list[x]

If you want to not modify the list in the using loop, which requries 
checking the new length each time (don't know how expensive this is in 
py)

-- 
Philip Sw "Starweaver" [rasx] :: www.rubydragon.com



More information about the Python-list mailing list