Extracting from a list

Cliff Wells logiplexsoftware at earthlink.net
Wed Apr 10 19:03:20 EDT 2002


On Wed, 10 Apr 2002 15:52:51 -0700
Jeff Shannon wrote:

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

Although slightly modified it would work:

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

I agree in principle that modifying a list that is being iterated over is
somewhat risky.

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308





More information about the Python-list mailing list