Extracting from a list

Jeff Shannon jeff at ccvcorp.com
Wed Apr 10 18:52:51 EDT 2002


In article <Xns91EC96C0C8E9CRASXnewsDFE1 at 130.133.1.4>, 
starx at pacbell.net says...
> Joel Bender || Wed 10 Apr 2002 01:35:10p:
> 
> > 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.
> 
> 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

This will *not* work as expected.

When you del list[I], then list[I+1] becomes list[I].  You then 
increment I, and get the next item... except that the item you 
get is the one that *used* to be list[I+2].  You skip an item 
each time you delete an item.

>>> mylist = range(5)
>>> mylist
[0, 1, 2, 3, 4]
>>> I = 0
>>> while I < len(mylist):
... 	if mylist[I] < 3:
... 		print mylist[I]
... 		del mylist[I]
... 	I += 1
... 
0
2
>>> mylist
[1, 3, 4]
>>> # note that 1 got skipped!

This is why it's always dangerous to modify the list you're 
iterating over.  It can be done safely (see Daniel's back-to-
front method), but it takes some work.

(As a side note, don't use list as an identifier name, since 
you're masking the builtin function list() ... )

-- 

Jeff Shannon
Technician/Programmer
Credit International



More information about the Python-list mailing list