Python zip behavour - Can someone explain this [duplicate]
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)))