Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python zip behavour – Can someone explain this

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading