Issue
I was in Jupyter Notebook playing around with the zip
function in Python, when I noticed a print statement wasn't printing. This is the code contained in the cell:
z1=["a","b","c"]
z2=[1,2,3]
collect=zip(z1,z2)
print(list(collect))
for index,(item1,item2) in enumerate(collect):
print(f"{index} corresponding to {item1} and {item2}")
And this code outputs
[('a', 1), ('b', 2), ('c', 3)]
Jupyter completely ignores the print statement in the for loop!
However, I noticed that if I comment out the first print statement, the print statements in the for loop then print. So, if the code in the cell is
z1=["a","b","c"]
z2=[1,2,3]
collect=zip(z1,z2)
#print(list(collect))
for index,(item1,item2) in enumerate(collect):
print(f"{index} corresponding to {item1} and {item2}")
then the output becomes
0 corresponding to a and 1
1 corresponding to b and 2
2 corresponding to c and 3
Something also very peculiar, is that if I change the print statement in the cell to something else, say print(collect)
, both print statements then print. I.e. if I change the code to
z1=["a","b","c"]
z2=[1,2,3]
collect=zip(z1,z2)
print(collect)
for index,(item1,item2) in enumerate(collect):
print(f"{index} corresponding to {item1} and {item2}")
the output becomes
<zip object at 0x7fadf85db0c0>
0 corresponding to a and 1
1 corresponding to b and 2
2 corresponding to c and 3
This is super weird!!! I am just wondering if anyone knows why this is happening, or how to fix it? I've been having a few problems with printing in Jupyter Notebook to be honest. Thank you.
Solution
This has nothing to do with Jupyter Notebook, actually, but rather with what zip
returns.
zip
returns an iterator object. Once you exhaust it (for example, by creating a list from all of its elements), it is empty and iterating over it is equivalent to iterating over empty collection.
That's why printing list(collect)
prevents it from working, while anything else will work just fine.
You can easily see that by repeating that print statement:
z1=["a","b","c"]
z2=[1,2,3]
collect=zip(z1,z2)
print(list(collect)) # [('a', 1), ('b', 2), ('c', 3)]
print(list(collect)) # []
Answered By - matszwecja
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.