Unexpected behavior clogging an iterator with a sequence

While trying to solve a specific code golf question, I came across a specific scenario that I had a hard time understanding the behavior with.

The script was: zip

with an iterator with a sequence, and after the transpose operation, the iterator passed the expected element.

>>> l = range(10)
>>> it = iter(l)
>>> zip(it, range(5))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> next(it) #expecting 5 here
6 

      

Am I missing something obvious?

Note Please provide reliable links to answers that may not be obvious.

+3


source to share


2 answers


I suspect it is being 5

consumed when zip

trying to zip up the following items. Zip stops when one of its arguments is "empty":

>>> l = range(10)
>>> it = iter(l)
>>> zip(range(5),it)
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> it.next()
5

      



By reversing the order, zip knows it can stop and not use the next item from it

+3


source


If you need links you can check the izip documentation . It gives an equivalent implementation:

def izip(*iterables):
    iterators = map(iter, iterables)
    while iterators:
        yield tuple(map(next, iterators))

      



Since it is expected list(izip(*args))

to have the same behavior as zip(*args)

, the result you get is actually logical behavior.

+1


source







All Articles