1

Created two lists in python and zipped them using zip function and saved them to a variable. Tried to print it to the console and was able to print successfully and when i tried again,empty list is printed.screenshot Same with tuples.screenshot

Why i am able to retrieve values only once? Am in doing something wrong?

Python 3.7.1

Naga
  • 23
  • 1
  • 6
  • 1
    [Please do not post code as images.](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question) – U13-Forward Dec 26 '18 at 03:15

2 Answers2

0

The zip function is actually just an iterator -- an iterator can only be traversed once. If you want to be able to iterate over it multiple times, convert it to a list first.

a = [1,2,3]
b = [1,2,3]
c = list(zip(a, b))
Russell Cohen
  • 717
  • 4
  • 7
0

Why is this?

Because those are similar to generators, so you can print first time, but when you try to print it again, it starts from the end, and no values left, see an example (clearer than yours):

>>> l=[1,2,3,4]
>>> it=iter(l) # generator basically (as in your question, zip, is also considered as a geneartor here)
>>> list(it)
[1, 2, 3, 4]
>>> list(it)
[]
>>> 

So how to solve this issue?

Simply just replace this line:

zipped_list = zip(list1,list2)

With:

zipped_list = list(zip(list1,list2))

Then everything would work fine.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114