[FRPythoneers] using pop() on a list

Uche Ogbuji uche.ogbuji at fourthought.com
Fri Jan 3 23:12:53 MST 2003


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

Wow.  Hmm.  Where to even start  :-)

Sean, I think, has the hunch on the best general solution here:

Sean Reifschneider: "I don't know what you have to do to get a list to be 
iteratorable."

iter() is the magic:

>>> l = [1,2,3,4,5,6]
>>> for i in iter(l):
...     if i == 4: l.pop(4)
...     print i
...
1
2
3
5
4
6
>>> print l
[1, 2, 3, 4, 6]

Just what you want, I think.  l is modified as you wish, but the iteration is 
not disturbed.

I call this the best "general" solution, because I presume you want to mod the 
list in place, and not create another list (say the real list has millions of 
entries").

If you don't mind creating another list, list comprehensions are your friend:

>>> l = [1,2,3,4,5,6]
>>> l1 = [ i for i in l if i != 4 ]
>>> print l1
[1, 2, 3, 5, 6]
>>> print l
[1, 2, 3, 4, 5, 6]

Notice how I had to negate the condition because the list comp *keeps* all 
items that you *don't* say you *don't* want.

Yeah.  Better dust off the old De Morgan's law  ;-)

There are *many* other ways to do what you want to do, but I just offered the 
two ways I'd choose to do it, depending on my tolerance for duped lists.

I hope this helps.  I must say that the richness that list comprehensions, 
generators and iterators have brought to Python are well nigh immeasurable.


-- 
Uche Ogbuji                                    Fourthought, Inc.
http://uche.ogbuji.net    http://4Suite.org    http://fourthought.com
A Python & XML Companion - http://www.xml.com/pub/a/2002/12/11/py-xml.html
XML class warfare - http://www.adtmag.com/article.asp?id=6965
MusicBrainz  metadata - http://www-106.ibm.com/developerworks/xml/library/x-thi
nk14.html





More information about the FRPythoneers mailing list