[FRPythoneers] using pop() on a list

Erick Bodine erick at allocity.com
Thu Jan 2 12:40:50 MST 2003


Thank you (& Sean), for the explanation & the code.  I am going to look
into iterators, there might be some interesting possibilities.

--ERick

-----Original Message-----
From: Bob Gailer [mailto:ramrom at earthling.net] 
Sent: Thursday, January 02, 2003 12:07 PM
To: frpythoneers at lists.community.tummy.com
Subject: Re: [FRPythoneers] using pop() on a list

At 10:45 AM 1/2/2003 -0700, Erick Bodine wrote:
>I want to loop over
>the list checking each item in the list for a condition & the then
pop()
>the matching item.  When I do this, the 'for' loop skips the item
>immediately following the pop but continues w/ the remainder of the
>items in the list.



>x = [1,2,3,4,5,6]
>i = 0
>for w in x:
>         print "Before: ", w
>         if w == 4:
>                 h = x.pop(i)
>                 print "Popped", h
>                 print "After pop: ", w
>         print "After: ", w
>         i += 1
>
>Before:  1
>After:  1
>Before:  2
>After:  2
>Before:  3
>After:  3
>Before:  4
>Popped 4
>After pop:  4
>After:  4
>Before:  6
>After:  6

When you pop the list shrinks by one element, but the iterator does not 
know that. The item following the one popped is now in the position of
the 
popped item, and the iterator moves to the next (6 in this case).

Try this:
i = 0
while i < len(x):
     if x[i] == 4:
         h = x.pop(i)
     else:
         i += 1

Bob Gailer
mailto:ramrom at earthling.net
303 442 2625



More information about the FRPythoneers mailing list