why return empty list when calling list on zip twice

Question:

As below python code shows, why it prints empty list when call the second list(ll)?

l1 = [1,2,3]
l2 = [4,5,6]
ll = zip(l1,l2,l1,l2)
ll
<zip at 0x23d50b10f40>
list(ll)
[(1, 4, 1, 4), (2, 5, 2, 5), (3, 6, 3, 6)]
ll
<zip at 0x23d50b10f40>
list(ll)
[]
Asked By: macyou

||

Answers:

Because zip is an Iterator object. When you call list(ll) for the first time, the values in the zip objects, get consumed. That is why when you call list again, there is nothing else to show.

zip is a function, that when applied on iterables, returns an iterator. Meaning, unless it is being iterated on, it does not calculate any value.

For example:

>>> z = zip([1, 2, 3], [3, 4, 5])
>>> z
<zip at 0x1e46824bec0>

>>> next(z)    # One value is computed, thus consumed, now if you call list:
(1, 3)

>>> list(z)    # There were only two left, and now even those two are consumed
[(2, 4), (3, 5)]

>>> list(z)    # Returns empty list because there is nothing to consume
[]
Answered By: user12337609
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.