Re: iterate over list while changing it

2009-10-01 Thread Simon Forman
On Wed, Sep 30, 2009 at 11:19 PM, Daniel Stutzbach wrote: > On Thu, Sep 24, 2009 at 3:32 PM, Torsten Mohr wrote: >> >> a = [1, 2, 3, 4, 5, 6] >> >> for i, x in enumerate(a): >>    if x == 3: >>        a.pop(i) >>        continue >> >>    if x == 4: >>        a.push(88) >> >>    print "i", i, "x",

Re: iterate over list while changing it

2009-09-30 Thread Daniel Stutzbach
On Thu, Sep 24, 2009 at 3:32 PM, Torsten Mohr wrote: > a = [1, 2, 3, 4, 5, 6] > > for i, x in enumerate(a): >if x == 3: >a.pop(i) >continue > >if x == 4: >a.push(88) > >print "i", i, "x", x > > I'd like to iterate over a list and change that list while iteratin

Re: iterate over list while changing it

2009-09-30 Thread Дамјан Георгиевски
>> a = [1, 2, 3, 4, 5, 6] >> >> for i, x in enumerate(a): > > If you change a list while iterating over, start at the tail. > > ...reversed(enumerate(a)) Python 2.6.2 (r262:71600, Jul 20 2009, 02:19:59) >>> a = [1, 2, 3, 4, 5, 6] >>> reversed(enumerate(a)) Traceback (most recent call last):

Re: iterate over list while changing it

2009-09-30 Thread Aahz
In article , Terry Reedy wrote: >Torsten Mohr wrote: >> >> a = [1, 2, 3, 4, 5, 6] >> >> for i, x in enumerate(a): > >If you change a list while iterating over, start at the tail. This only applies if you add/remove elements; simply updating elements does not require starting at the tail. -- A

Re: iterate over list while changing it

2009-09-25 Thread Warpcat
iterate over a copy of the list: for i, x in enumerate(a[:]): Always worked for me ;) -- http://mail.python.org/mailman/listinfo/python-list

Re: iterate over list while changing it

2009-09-24 Thread Rhodri James
On Thu, 24 Sep 2009 21:32:53 +0100, Torsten Mohr wrote: Hello, a = [1, 2, 3, 4, 5, 6] for i, x in enumerate(a): if x == 3: a.pop(i) continue if x == 4: a.push(88) print "i", i, "x", x I'd like to iterate over a list and change that list while iterating.

Re: iterate over list while changing it

2009-09-24 Thread Simon Forman
On Thu, Sep 24, 2009 at 4:32 PM, Torsten Mohr wrote: > Hello, > > a = [1, 2, 3, 4, 5, 6] > > for i, x in enumerate(a): >    if x == 3: >        a.pop(i) >        continue > >    if x == 4: >        a.push(88) > >    print "i", i, "x", x > > I'd like to iterate over a list and change that list whil

Re: iterate over list while changing it

2009-09-24 Thread Terry Reedy
Torsten Mohr wrote: Hello, a = [1, 2, 3, 4, 5, 6] for i, x in enumerate(a): If you change a list while iterating over, start at the tail. ...reversed(enumerate(a)) if x == 3: a.pop(i) del a[i] # you already have the item continue if x == 4: a.push(88)

iterate over list while changing it

2009-09-24 Thread Torsten Mohr
Hello, a = [1, 2, 3, 4, 5, 6] for i, x in enumerate(a): if x == 3: a.pop(i) continue if x == 4: a.push(88) print "i", i, "x", x I'd like to iterate over a list and change that list while iterating. I'd still like to work on all items in that list, which is n