[Python-ideas] Use the plus operator to concatenate iterators

Chris Angelico rosuav at gmail.com
Wed Aug 5 06:29:17 CEST 2015


On Wed, Aug 5, 2015 at 1:01 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> Repetition on an arbitrary iterator is ambiguous. If I say, "repeat the
> list [1,2,3] twice" there is no ambiguity, I must get [1, 2, 3, 1, 2, 3]
> or there is some problem. But iterators can have non-deterministic
> lengths and values:
>
> def gen():
>     while random.random() < 0.9:
>         yield random.random()
>
> What does it mean to "repeat gen twice"? It might mean either of:
>
> - generate one run of values using gen, then repeat those same values;
>
> - generate two runs of values using gen.

Actually, that's a generator, which is an example of an *iterable*,
not an *iterator*. An iterator would be gen(), not gen. There's no
logical way to go back to the iterator's source and say "Please sir, I
want some more"; compare:

x = iter([1,2,3,4,5])
next(x); next(x)
print(list(x*2))

What does "doubling" an iterator that's already partly consumed do?
Asking to go back to the original list is wrong; asking to duplicate
(by caching) the results that we'd already get makes sense. With a
generator, it's no different - you could chain two generator objects
called from the same function, but the generator object doesn't know
what function it was called from (at least, I don't think it does).

So there's only one possible meaning for doubling an iterator, and it's list(x).

ChrisA


More information about the Python-ideas mailing list