Lokeshwar Tailor
Lokeshwar Tailor

Reputation: 371

Statements in for-loop not getting printed after using 'list(zip_variable)', but getting printed before using 'list(zip_variable)'

The statement "Hello before using list(zip_shop)" is getting printed.

The statement "Hello after using list(zip_shop)" is not getting printed.

groceries = ["apple","chips","bread","icecream"]
price = [2,3,1.2,4.25]
print("groceries = ",groceries,"and price =",price)

zip_shop = zip(groceries,price)

print("zip_shop =", zip_shop,"and type(zip_shop) =",type(zip_shop),"and id(zip_shop) = ",id(zip_shop))
for g, p in zip_shop:
    print("Hello before using list(zip_shop)")


print("list(zip_shop)=", list(zip_shop),"and type(zip_shop) =",type(zip_shop),"and id(zip_shop) = ",id(zip_shop))
for g, p in zip_shop:
    print("Hello after using list(zip_shop)")

Can someone please help me understand the behavior here?

Output is as below:

groceries =  ['apple', 'chips', 'bread', 'icecream'] and price = [2, 3, 1.2, 4.25]
zip_shop = <zip object at 0x0000022852A29948> and type(zip_shop) = <class 'zip'> and id(zip_shop) =  2372208335176
Hello before using list(zip_shop)
Hello before using list(zip_shop)
Hello before using list(zip_shop)
Hello before using list(zip_shop)
list(zip_shop)= [] and type(zip_shop) = <class 'zip'> and id(zip_shop) = 2372208335176

Process finished with exit code 0

Upvotes: 0

Views: 55

Answers (2)

Shivam Arora
Shivam Arora

Reputation: 364

You are using the zip object in wrong way. Zip object iterators are Lazily evaluated which means that they are only evaluated when they are called and not evaluated more than once, this avoids repeated evaluation of the zip object. You have to call Zip() for iterative object when you want to iterate.

groceries = ["apple","chips","bread","icecream"]
price = [2,3,1.2,4.25]
print("groceries = ",groceries,"and price =",price)

#zip_shop = zip(groceries,price)

for g, p in zip(groceries,price):
    print("Hello before using list(zip_shop)")

print("List:",list(zip(groceries,price)))

for g, p in zip(groceries,price):
    print("Hello after using list(zip_shop)")

Upvotes: 0

georgexsh
georgexsh

Reputation: 16624

In Python 3, the zip function yields an iterator, which can only be consumed once, you have to convert it to a list:

zip_shop = list(zip(groceries, price))

Upvotes: 2

Related Questions