Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing an unzipped list object returns empty list [duplicate]

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?

like image 381
Perspicacious Avatar asked May 18 '20 16:05

Perspicacious


People also ask

What is the nature of empty list in Java?

These empty list are immutable in nature. Following is the declaration of emptyList () method: This method does not accept any parameter. The emptyList () method returns an empty immutable list.

How to create an empty list in Python?

Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise. I really hope that you liked my article and found it helpful. Now you can create empty lists in your Python projects. Check out my online courses.

What is the parameter of emptylist () method?

Following is the declaration of emptyList () method: This method does not accept any parameter. The emptyList () method returns an empty immutable list.

How to get a list with no elements in Java?

The emptyList () method of Java Collections class is used to get a List that has no elements. These empty list are immutable in nature. Following is the declaration of emptyList () method: This method does not accept any parameter. The emptyList () method returns an empty immutable list.


Video Answer


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

like image 100
Luka Mesaric Avatar answered Oct 18 '22 00:10

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.

like image 2
Pavel Botsman Avatar answered Oct 18 '22 02:10

Pavel Botsman