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",
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
>> 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):
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
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
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.
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
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)
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