[FRPythoneers] using pop() on a list

Mike Olson Mike.Olson at fourthought.com
Sun Jan 5 17:00:19 MST 2003


On Thu, 2003-01-02 at 10:45, Erick Bodine wrote:
> I am having some trouble w/ using pop on a list.  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.  Any ideas on how to get around this, any help would
> be much appreciated (See code example below)

Your destroying the list as you iterate over it.  The easy fix is to
change your for loop to

for w in x[:]:

of course, this only works for very small lists.  there are other
solution, but it really depends on what your trying to do.

Mike

> 
> 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
> 
> ** Where did list item '5' go??
> 
> --ERick
> _______________________________________________
> This message sent by the FRPythoneers mailing list.
> Unsubscribe: echo unsubscribe | FRPythoneers-request at lists.community.tummy.com
> URL: http://lists.community.tummy.com/mailman/listinfo/frpythoneers
-- 
Mike Olson                                Principal Consultant
mike.olson at fourthought.com                +1 303 583 9900 x 102
Fourthought, Inc.                         http://Fourthought.com 
PO Box 270590,                            http://4Suite.org
Louisville, CO 80027-5009, USA
XML strategy, XML tools, knowledge management




More information about the FRPythoneers mailing list