writable iterators?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jun 22 21:50:50 EDT 2011


On Thu, 23 Jun 2011 09:10 am Neal Becker wrote:

> Steven D'Aprano wrote:
> 
>> On Wed, 22 Jun 2011 15:28:23 -0400, Neal Becker wrote:
>> 
>>> AFAICT, the python iterator concept only supports readable iterators,
>>> not write. Is this true?
>>> 
>>> for example:
>>> 
>>> for e in sequence:
>>>   do something that reads e
>>>   e = blah # will do nothing
>>> 
>>> I believe this is not a limitation on the for loop, but a limitation on
>>> the python iterator concept.  Is this correct?
>> 
>> Have you tried it? "e = blah" certainly does not "do nothing", regardless
>> of whether you are in a for loop or not. It binds the name e to the value
>> blah.
>> 
> 
> Yes, I understand that e = blah just rebinds e.  I did not mean this as an
> example of working code.  I meant to say, does Python have any idiom that
> allows iteration over a sequence such that the elements can be assigned?

Yes. I already gave one:

for i, e in enumerate(seq):
    seq[i] = e + 42


If you look at code written before the enumerate built-in, you will often
find code like this:

for i in range(len(seq)):
    e = seq[i]
    seq[i] = e + 42


Sometimes you'll find code that does this:

i = 0
while i < len(seq):
    e = seq[i]
    seq[i] = e + 42
    i += 1

but don't do that, it's slow.

Or you can do this:

seq[:] = [e+42 for e in seq]

There are others.

[...]
> AFAIK, the above is the only python idiom that allows iteration over a
> sequence
> such that you can write to the sequence.  And THAT is the problem.  In
> many cases, indexing is much less efficient than iteration.

Are you aware that iteration is frequently based on indexing?

In the cases that it isn't, that's because the iterator generates values
lazily, without ever storing them. You *can't* write to them because
there's nowhere to write to! If you want to store the values so they are
writable, then you have to use indexing.

What makes you think that this is a problem in practice? Can you give an
example of some task you can't solve because you (allegedly) can't write to
a sequence?


-- 
Steven




More information about the Python-list mailing list