All discussion is about python 3.1.2; see Python docs for the source of my question.
I know what zip
does; I just don't understand why it can be implemented like this:
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
iterables = map(iter, iterables)
while iterables:
yield tuple(map(next, iterables))
Let's say I call zip(c1, c2, c3)
. If I understand correctly, iterables is initially the tuple (c1, c2, c3).
The line iterables = map(iter, iterables)
converts it to an iterator that would return iter(c1), iter(c2), iter(c3) if iterated through.
Inside the loop, map(next, iterables)
is an iterator that would return next(iter(c1))
, next(iter(c2))
, and next(iter(c3))
if iterated through. The tuple
call converts it to (next(iter(c1)), next(iter(c2)), next(iter(c3))
, exhausting its argument (iterables
) on the very first call as far as I can tell. I don't understand how the while
loop manages to continue given that it checks iterables
; and if it does continue why the tuple
call doesn't return empty tuple (the iterator being exhausted).
I'm sure I'm missing something very simple..