Iterator, modify data in loop body

Chris Angelico rosuav at gmail.com
Sat Sep 13 11:32:48 EDT 2014


On Sun, Sep 14, 2014 at 1:27 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> 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.

Sure it will - that's kinda the point of a double-ended queue, to
avoid all the inefficient movements :) But the concept is still the
same: do repeated mutations rather than iteration. Either that, or
iterate and build up a new list, either with a comprehension or with
something like this:

newlst = []
for element in lst:
    # work with element
    newlst.append(new_element)

ChrisA



More information about the Python-list mailing list