On Sun, Sep 14, 2014 at 1:27 AM, Ian Kelly <ian.g.ke...@gmail.com> wrote: > On Sat, Sep 13, 2014 at 1:39 AM, Michael Welle <mwe012...@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 -- https://mail.python.org/mailman/listinfo/python-list