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?
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.
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.
Following is the declaration of emptyList () method: This method does not accept any parameter. The emptyList () method returns an empty immutable list.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With