To better understand Python's generator I'm trying to implement facilities in the itertools
module, and get into trouble with izip
:
def izip(*iterables):
its = tuple(iter(it) for it in iterables)
while True:
yield tuple(next(it) for it in its) # ERROR
# yield tuple(map(next, its)) # OK
My code uses the ERROR line, and the reference implementation (given in the manual) uses the OK line, not considering other tiny differences. With this snippet:
for x in izip([1, 2, 3], (4, 5)):
print x
My code outputs:
(1, 4)
(2, 5)
(3,)
()
()
... # indefinite ()
, while the expected output is:
(1, 4)
(2, 5)
What's wrong with my code, please?
izip() izip() returns an iterator that combines the elements of the passed iterators into tuples. It works similarly to zip() , but returns an iterator instead of a list.
Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.
The reason your implementation does not work is because the StopIteration
exception caused by one of the iterables being exhausted is thrown inside a generator expression. It will only terminate the generator expression, not the enclosing generator function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With