Why is this code giving empty tuple and dictionary as output? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why is this code giving empty tuple and dictionary as output?

a = (1, 2, 3) b = ("one", "two", "three") c = zip(a, b) print(list(c)) print(tuple(c)) print(dict(c))

23rd Oct 2022, 6:31 AM
Shantanu
Shantanu - avatar
1 Answer
+ 10
Shantanu , the code is giving a list output as expected. the other outputs for tuple and dict are empty. the reason for this behaviour is: > zip() creates a zip class object / instance. > using a constructor like list(), tuple() or dict() creates the desired output by implicitly using an iterator. instead of using the mentioned constructors, we can use a for loop with the same effect. > iterator can only be used once, then it get exhausted. this is given by the implementation of python. so in this case, only the first output prints correctly. if the line with the list creation is commented out, the tuple will print correctly.
23rd Oct 2022, 7:40 AM
Lothar
Lothar - avatar