planetp
planetp

Reputation: 16115

How does the sample code for izip work?

I'm trying to understand the "equivalent code" for izip from the docs.

def izip(*iterables):
    # izip('ABCD', 'xy') --> Ax By
    iterators = map(iter, iterables)
    while iterators:
        yield tuple(map(next, iterators))

Since iterators is a non-empty list, shouldn't this produce an infinite loop?
Also I tried to put print iterators to the bottom of the function, but it never got executed. Why?

Upvotes: 1

Views: 84

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123400

When an iterator is exhausted, it raises StopIteration when next() is called on it.

Thus, the tuple(map(next, iterators)) will propagate the StopIteration exception to the caller, interrupting the infinite loop.

Upvotes: 3

Related Questions