wdscxsj
wdscxsj

Reputation: 860

Why does this implementation of izip() not work?

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?

Upvotes: 8

Views: 173

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 602115

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.

Upvotes: 12

Related Questions