Iterator, modify data in loop body

Chris Angelico rosuav at gmail.com
Tue Sep 16 11:19:28 EDT 2014


On Tue, Sep 16, 2014 at 6:49 PM, Thomas Rachel
<nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de>
wrote:
> Am 13.09.2014 09:22 schrieb Chris Angelico:
>
>> 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)
>
>
> And if you don't like that, define a
>
> def iter_pop(lst):
>     while lst:
>         yield lst.pop(0)
>
> and you can do
>
>     for element in iter_pop(lst):

But that's exactly the same thing, with another level of indirection.
It certainly isn't the advantage you'd expect from an iterator, namely
that it simply stores a marker that gets advanced to the next element.
Popping the 0th element is costly, wrapping it into an iterator
conceals that.

ChrisA



More information about the Python-list mailing list