Separate for loops in zip objects with different loop variables

Hello, I’m new to coding and learning about the zip function. I’m using PyCharm Community Edition 2023.3.4 with Python 3.12.0. I’m guessing it’s better to type the actual code than describing stuff, so here goes:

first = ["a", "b", "c"]
second = ["x", "y", "z"]

zip_variable = zip(first, second)

for x in zip_variable:
print(x)

for i, j in zip_variable:
print(i, j)

regardless of which loop I run first, the first one runs just fine the message “Process finished with exit code 0” appears. It’s like the code executes up to the first loop and then just finishes. Any help is appreciated!

P.S. This is my first time posting on any forum regarding coding so I don’t know if I did the preformatted text thing correctly. Is it okay or should I not have added these things ` to every single line?

zip creates an Iterator.
Iterators only iterate through each of their values once (deliberately, e.g. to reduce memory use).
To iterate over the same values again, a new Iterator must be created.

first = ["a", "b", "c"]
second = ["x", "y", "z"]

zip_variable = zip(first, second)

for x in zip_variable:
  print(x)

zip_variable = zip(first, second)
for i, j in zip_variable:
  print(i, j)

There’s nothing wrong with the way you’ve written it, but for brevity it’s normal just to put short expressions of zipped iterables straight into the for loop line (for code reuse of more complicated expressions defining an iterator, a generator function could be used):

first = ["a", "b", "c"]
second = ["x", "y", "z"]

for x in  zip(first, second):
  print(x)

for i, j in  zip(first, second):
  print(i, j)
1 Like

Reference:

Understood! Thank you!