1

just out of curiosity I wanted to ask, why is the following wanted behavior in Python?

Suppose we have:

a = [1,2,3]
b = [1,2,3]
c = [1,2,3,4]
ai = iter(a)
bi = iter(b)
ci = iter(c)

Now, I expected the following example to print [4], however, it prints [].

for _ in zip(ci, zip(ai, bi)):
    pass

print(list(ci))

Console:

>>> print(list(ci))
[]

But when I change arguments of the outter zip, it prints what I expect ([4]).

for _ in zip(zip(ai, bi), ci):
    pass

print(list(ci))

Console:

>>> print(list(ci))
[4]

Shouldn't both example print the same result? Thanks.

1 Answers1

2

next() of a zip iterator will try to read the next element of each of its argument iterators in order. If any of them reports that it's exhausted, the zip iterator will stop and report that it's exhausted.

This means that it will perform an extra iteration on all the initial arguments that are longer than the shortest one. This means that it reads an extra element of c.

You can see this ordering and extra iteration in the equivalent code in the documentation.

Change c to [1, 2, 3, 4, 5] and you'll get [5] at the end.

Barmar
  • 741,623
  • 53
  • 500
  • 612