-1
m = ['a', 'b', 'c', 'd']
n = list(range(1,5))
l = zip(m,n)
x = list(l)
print(x)
print(list(l))

The second print is an empty list. Why?

Why not get the same output as the first print?

kile
  • 141
  • 1
  • 7
  • 3
    In Python 3 `zip` objects are generators. Once used they are exhausted. – Klaus D. Sep 06 '20 at 05:26
  • Specifically, `x = list(l)` exhausts the generator `l`. Then, when you try to reuse `l`, the data you get is nothing. If the final line was `print(list(zip(m, n)))`, it work work, because that would be a *new* generator. See the dupe this question was closed against for more detail. – paxdiablo Sep 06 '20 at 05:30
  • zip() returns an iterator, more like you use index while iterating through loops. Outside the loop, you cant access the index/iterator. For more info and examples, you can read through the docs -https://docs.python.org/3.3/library/functions.html#zip – Ganesh Jadhav Sep 06 '20 at 05:42

1 Answers1

1

Zip returns an iterator. Once you consume the iterator then it will continue to return empty.

If you consume the iterator with list(), then you’ll see an empty list as well.

https://realpython.com/python-zip-function/

Edward Romero
  • 2,905
  • 1
  • 5
  • 17