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?
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.