1

I am performing this simple zip in python from a dictionary and I am not sure why the second time I do it it gives me an empty list.

l1= {'a':6, 'b':5, 'c':3, 'd':2, 'e':1, 'f':7, 'g':4, 'h':9}
l2={'a':7, 'b':5, 'c':2, 'd':3, 'e':8}

z=zip(l1.values(),l2.values())

print(list(z)) #This gives me correct output.
print(list(z)) #This gives me EMPTY list. WHY?

[(6, 7), (5, 5), (3, 2), (2, 3), (1, 8)]
[]
Arpit
  • 333
  • 2
  • 9
  • 3
    `zip` along with `range` are generator type objects, meaning they do not store all the data in memory, they instead yield each data point. In that way the generator is exhausted after the first line. – ChrisOram Feb 09 '22 at 14:52
  • 1
    If you want to be able to iterate over the zip more than once, store it as a list up front: `z = list(zip(l1.values(), l2.values()))` – Samwise Feb 09 '22 at 14:53

1 Answers1

2

you can use zip one time because it iter object

you can convert it to list object

import copy
l1= {'a':6, 'b':5, 'c':3, 'd':2, 'e':1, 'f':7, 'g':4, 'h':9}
l2={'a':7, 'b':5, 'c':2, 'd':3, 'e':8}

z=list(zip(l1.values(),l2.values()))
print(list(z)) #This gives me correct output.
print(list(z)) #This gives me EMPTY list. WHY?

output

[(6, 7), (5, 5), (3, 2), (2, 3), (1, 8)]
[(6, 7), (5, 5), (3, 2), (2, 3), (1, 8)]
tomerar
  • 805
  • 5
  • 10