iterate over list while changing it

Simon Forman sajmikins at gmail.com
Thu Oct 1 14:27:29 EDT 2009


On Wed, Sep 30, 2009 at 11:19 PM, Daniel Stutzbach
<daniel at stutzbachenterprises.com> wrote:
> On Thu, Sep 24, 2009 at 3:32 PM, Torsten Mohr <tmohr at s.netic.de> 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 iterating.
>> I'd still like to work on all items in that list, which is not happening
>> in the example above.
>
> I assume that by "a.push" you meant "a.append".
>
> I believe this will do what you want:
>
> a = [1, 2, 3, 4, 5, 6]
> i = 0
> while i < len(a):
>    x = a[i]
>    if x == 3:
>        a.pop(i)
>        i += 1
>        continue
>
>    if x == 4:
>        a.append(88)
>
>    print "i", i, "x", x
>    i += 1
>
> --
> Daniel Stutzbach, Ph.D.
> President, Stutzbach Enterprises, LLC
>


In the case of x == 3 when you remove an item from the list you should
not increment the index.



More information about the Python-list mailing list