0

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)
[]
macyou
  • 99
  • 6

1 Answers1

3

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
[]