M. Klugerford M. Klugerford - 4 months ago 10
Python Question

Python behavior in loops

I have the following code:

a = ['bobby', 'freddy', 'jason']
b = ['pep', 'lin', 'cat']

for a in b:
for b in a:
print a,b


I'd assume that after the first iteration of the outer loop, since the global variable
b
has been modified, and is now a
str
of length 1, the iteration would stop. But it doesn't do so.

Output:

pep p
pep e
pep p
lin l
lin i
lin n
cat c
cat a
cat t


So the basic question is, when the for loop is created, does it store a copy of the iterator and then loop through that even if the original variable now "points" to a different value?

Answer

when the for loop is created, does it store a copy of the iterator and then loop through that even if the original variable now "points" to a different value?

Yes! You identified it correctly. Typically, when such looping constructs occur, the interpreter calls iter(object) and uses the returned iterator object for iteration. It does not matter if the original variable name is bound to some other object post this step.