Why does using a list function on a zipped list cause an issue with dict comprehension

I was printing my variable to check my code as I went though the Dict Comprehensions Lesson in my data scientist career path. When I used this code below the drinks_to_caffeine would print as an empty dictionary.

drinks = ["espresso", "chai", "decaf", "drip"]
caffeine = [64, 40, 0, 120]

zipped_drinks = zip(drinks, caffeine)
print(list(zipped_drinks))
drinks_to_caffeine = {key: value for key, value in zipped_drinks}
print(drinks_to_caffeine)

After some troubleshooting I found that if I didn’t print the zipped_drinks (or without using the list function to print it) that drinks_to_caffeine would print as expected. Why does this happen? What is the list function doing to the zipped_drinks to cause this issue?

That line is consuming the iterator.

Witness:

arr = [2, 3, 5, 7, 11, 13, 17]
mapped_arr = map(lambda x: x ** 2, arr)    # map object is an iterator
while mapped_arr:
    print (next(mapped_arr))

    
4
9
25
49
121
169
289
Traceback (most recent call last):
  File "<pyshell#139>", line 2, in <module>
    print (next(mapped_arr))
StopIteration

print ([*mapped_arr])
[]
1 Like

When you zip 2 lists they come back as an iterator. If you want to print it then you have to use the list constructor on the zipped object, but this only works once. If you try to print again the same zipped list it will come back empty.

As far as I’ve researched this is done so we can save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you wan to have them available you have to assign them to a new empty list ( actually I believe it will come back as a tupple)

Hope this helped! :heart_decoration:

1 Like