Iterating over zip function using dictionary comprehension

Question:
Does anyone know why for the second instance, i get an empty dictionary when i try to iterate over the variable z but then returns a dictionary with items in instance1 when i use the zip function instead of the variable z?

Repl link:

https://replit.com/@jonathanessombe/learn-1#main.py

code snippet

#instance1
cities = ['mumbai', 'new york', 'paris']
countries = ['india', 'usa', 'france']
z = zip(cities, countries)
print(z)
for thing in z:
  print(thing)

dict = {city: country for city,country in zip(cities, countries)}
print(dict)

#instance2
cities = ['mumbai', 'new york', 'paris']
countries = ['india', 'usa', 'france']
z = zip(cities, countries)
print(z)
for thing in z:
  print(thing)

dict = {city: country for city,country in z}
print(dict)

Hello there @jonathanessombe

AFAIK in python a zip object is a iterator. And as iterator you can only iterate (is iterate right?) once.
After you iterated(?) you can’t do it again unless you recreate it.

So you iterate over z once here:

for thing in z:
  print(thing)

And after that you can’t iterate over it anymore.

So when you try to create a dictionary using z

dict = {city: country for city, country in z}

it will be empty since you already iterate over z before

Also, avoid using dict as a variable since dict is a built-in python class for dictionaries.

2 Likes

wdym by AFAIK?
wdym by you can’t iterate over it again unless you recreate it?
I iterated over the zip function once, so why am i still able to iterate over it again?

AFAIK = As Far As I Know

"So a function or other code that expects an iterable must not assume it will be able to iterate over the iterable more than once. If the iterable is also iterator it will be exhausted after the first iteration. For further iterations, that code or function will not get any items from the iterable (which is also iterator), which might break it.

Once the iterator is exhausted, it is of no use anymore. We can’t get any more items from iterable using exhausted iterator.
If we want to iterate over an iterable again, we need to get a new iterator from it"

Just to clarify:

In “instance1,” when you run the dictionary comprehension, you are using zip(cities, countries) directly. This creates a new zip object that is separate from z. Therefore, it starts fresh and hasn’t been iterated over.

dict = {city: country for city,country in zip(cities, countries)}

In “instance2,” you are using the same zip object z that you already iterated over with the for loop. That’s why you get an empty dictionary in this case.

dict = {city: country for city,country in z}
2 Likes