Printing an unzipped list object returns empty list

Question:

In the following code, I am trying to unzip a zip object.

x = [1, 2, 3]; y = ['a', 'b', 'c']

z = zip(x, y)
#print(list(z))                #2nd print statement returns [] if this line is uncommented

unzip = zip(*z)
print(list(unzip))             #returns [(1, 2, 3), ('a', 'b', 'c')]

If I keep the code as it is, it works normal. But on uncommenting the 1st print statement, the 2nd print statement returns an empty list instead of returning the unzipped list object. Why?

Asked By: Perspicacious

||

Answers:

zip returns an iterator. In Python, iterators can be consumed, meaning once you iterate over them, you cannot do it again. When you executed list(z), you consumed iterator z so unpacking it in zip(*z) gave you an empty iterator.

The idea behind consuming iterators is that they use very little space (complexity is O(1)), so you cannot iterate over them multiple times because that would mean you have to store all the values, leading to O(n) complexity. When you iterate over a collection multiple times, you are actually generating a new iterator every time.

Answered By: Luka Mesaric

This happens because zip function returns an iterator, not a new list. In other words, it can only be accessed once.
When you print it for the first time, interpretator loops through the result of this function.
Thus, you cannot access the results of the zip function second time.

Answered By: Pavel Botsman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.