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)]
>Solution :
z is a generator 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)))