Peek inside iterator (is there a PEP about this?)
kyrie at uh.cu
Wed Oct 1 16:46:33 CEST 2008
For most use cases I think about, the iterator protocol is more than enough.
However, on a few cases, I've needed some ugly hacks.
a = iter([1,2,3,4,5]) # assume you got the iterator from a function and
b = iter([1,2,3]) # these two are just examples.
has a different side effect from
After the excecution, in the first case, iterator a contains just , on the
second, it contains [4,5]. I think the second one is correct (the 5 was never
used, after all). I tried to implement my 'own' zip, but there is no way to
know the length of the iterator (obviously), and there is also no way
to 'rewind' a value after calling 'next'.
Will this iterator yield any value? Like with most iterables, a construct
# do something
would be a very convenient thing to have, instead of wrapping a 'next' call on
a try...except and consuming the first item.
# do something ... but the first true value was already consumed and
# cannot be reused. "Any" cannot peek inside the iterator without
# consuming the value.
i1, i2 = tee(iterator)
# do something with i2
Has there been any PEP regarding the problem of 'peeking' inside an iterator?
Knowing if the iteration will end or not, and/or accessing the next value,
without consuming it? Is there any (simple, elegant) way around it?
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
More information about the Python-list