writable iterators?
Chris Kaynor
ckaynor at zindagigames.com
Wed Jun 22 19:21:54 EDT 2011
You could probably implement something like this using generators and the
send method (note the example is untested and intended for 2.6: I lack
Python on this machine):
def gen(list_):
for i, v in enumerate(list_):
list_[i] = yield v
def execute():
data = range(10)
iterator = gen(data)
lastValue = iterator.next()
while True:
print lastValue
try:
lastValue = iterator.send(lastValue + 1)
except StopIteration:
break
print data
>>> execute()
0
1
2
3
4
5
6
7
8
9
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Chris
On Wed, Jun 22, 2011 at 4:10 PM, Neal Becker <ndbecker2 at gmail.com> 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?
>
> ...
> > * iterators are lazy sequences, and cannot be changed because there's
> > nothing to change (they don't store their values anywhere, but calculate
> > them one by one on demand and then immediately forget that value);
> >
> > * immutable sequences, like tuples, are immutable and cannot be changed
> > because that's what immutable means;
> >
> > * mutable sequences like lists can be changed. The standard idiom for
> > that is to use enumerate:
> >
> > for i, e in enumerate(seq):
> > seq[i] = e + 42
> >
> >
> 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.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110622/ae08e748/attachment-0001.html>
More information about the Python-list
mailing list