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.