1

Is a zip object available to use in for-loop only as the object itself?

I wish i can get some explanation why other types(like variable, list) can't be used when it is actually the same thing.

x = [1, 2, 3]
y = ['a', 'b', 'c']
​
obj1 = zip(x, y)
odj2 = list(zip(x, y))

​# working properly
for a, b in zip(x, y):
    print(a)
    print(b)     

# doesn't work and don't know why
for a, b in obj1:
    print(a)
    print(b)     

for a, b in obj2:
    print(a)
    print(b)  

so, do i have to use zip object as itself with zip function in for-loop?

Thanks a lot in advance!

jenna.h
  • 53
  • 1
  • 4

1 Answers1

6

If you run your provided code from the beginning, it works (except that odj2 should be obj2).

The reason for your confusion is that the zip object is an iterator. It does not store elements in memory, but rather generates them on the fly, as needed. You cannot access previous elements or restart an iterator; instead, you have to construct a new one. Therefore, if you find yourself needing to iterate through such sequences more than once, you should convert them to persistent data structures, such as lists. For example:

x = [1, 2, 3]
y = ['a', 'b', 'c']

zip_object = zip(x, y)

print('first time:')

for first, second in zip_object:
    print(first, second)

print('second time:')

for first, second in zip_object:
    print(first, second)

print('done')

Output:

first time
1 a
2 b
3 c
second time
done

Contrast this to the case where you use the zip object to create a list:

zip_object = zip(x, y)
new_list = list(zip_object)

print('first time:')

for first, second in new_list:
    print(first, second)

print('second time:')

for first, second in new_list:
    print(first, second)

print('going back to the zip object')

for first, second in zip_object:
    print(first, second)

print('done')

Output:

first time
1 a
2 b
3 c
second time
1 a
2 b
3 c
going back to the zip object
done

What happened is that you iterated through obj1 somewhere, then, without creating a new zip object, tried to iterate through it again. Since it was already fully exhausted, there was nothing for the for loop to iterate over.

gmds
  • 19,325
  • 4
  • 32
  • 58