Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this implementation of izip() not work?

Tags:

python

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?

like image 939
wdscxsj Avatar asked Apr 11 '12 14:04

wdscxsj


People also ask

What is Izip Python?

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.

Why Itertool is used in Python?

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.


1 Answers

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.

like image 96
Sven Marnach Avatar answered Oct 15 '22 10:10

Sven Marnach