Iterator, modify data in loop body

Chris Angelico rosuav at
Sat Sep 13 09:22:54 CEST 2014

On Sat, Sep 13, 2014 at 5:01 PM, Michael Welle <mwe012008 at> wrote:
> ideed, this works for the minimal example. In a real application list
> comprehension might be a bit unhandy, because there is a lot of code
> involved.

Sure. Sometimes, cutting something down for posting makes a completely
different solution possible, and that doesn't much help. :)

> It depends on the use case I think. For some algorithms it feels natural
> to just append at the end of the list while consuming elements from the
> front. I think a deque supports that as well.

In that case, don't iterate over the list at all. Do something like this:

while lst:
    element = lst.pop(0)
    # work with element

There's no mutation-while-iterating here, and it's clear that you'll
keep going until there's absolutely nothing left.


More information about the Python-list mailing list