Iterator, modify data in loop body

Ian Kelly ian.g.kelly at gmail.com
Sat Sep 13 17:27:23 CEST 2014


On Sat, Sep 13, 2014 at 1:39 AM, Michael Welle <mwe012008 at gmx.net> wrote:
>> In that case, don't iterate over the list at all. Do something like this:
>>
>> while lst:
>>     element = lst.pop(0)
>>     # work with element
>>     lst.append(new_element)
>>
>> There's no mutation-while-iterating here, and it's clear that you'll
>> keep going until there's absolutely nothing left.
> Ah, that looks like a good approach, thank you.

Also note that this approach (appending to the end and popping from
the front) will be more efficient using a collections.deque than a
list.



More information about the Python-list mailing list