[FRPythoneers] using pop() on a list

Bob Gailer ramrom at earthling.net
Thu Jan 2 12:07:10 MST 2003


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
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002


More information about the FRPythoneers mailing list