Python zip behavour – Can someone explain this

Question:

Can someone explain why the 4th print statement is returning an empty list?

x=[1]
y=[2]
z=zip(x,y)

print(z)
print(list(z))
print(z)
print(list(z))
print(list(zip(x,y)))

<zip object at 0x0000023F9382B688>
[(1, 2)]
<zip object at 0x0000023F9382B688>
[]
[(1, 2)]

Answers:

Edit: the answer previously stated ‘generator’ instead of ‘iterator’, but @juanpa.arrivillaga correctly pointed out that the zip object is in fact an iterator (which works essentially the same from a user perspective, but does not have the same overhead)

z is an iterator and your first use of it in print(list(z)) exhausts it. You should repeat z=zip(x,y) before the 4th print statement. Note that you still see it as a <zip object> in the 3rd print statement because it is, it’s just an exhausted zip object. And the first use doesn’t exhaust it.

x = [1]
y = [2]
z = zip(x,y)    # zip object created, ready to yield values

print(z)        # print z, the object
print(list(z))  # exhaust z into a list, print the list
print(z)        # print z, the object (now exhausted)
print(list(z))  # try to exhaust z into a list again, nothing there, print []

Try this:

x=[1]
y=[2]
z=zip(x,y)

print(z)
print(list(z))
print(z)
z=zip(x,y)
print(list(z))
print(list(zip(x,y)))
Answered By: Grismar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.