[FRPythoneers] using pop() on a list

Uche Ogbuji uche.ogbuji at fourthought.com
Fri Jan 3 23:41:51 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.

That's what I get for posting so late.  Of course the iteration is disturbed.

I'm not up right now for crafting a clever way to do it with iterators and 
excepting backwards traversal and list duplication.  Maybe tomorrow I'll think 
something up.  Or maybe I won't be able to.  For now, if you don't want to 
dupe the lists, some variation on Bob Gailer's suggestion should work.

Time for bed  ;-)

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