Asish M.
Asish M.

Reputation: 2647

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?

Upvotes: 2

Views: 72

Answers (2)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96287

Just to add, you can think of the iterator protocol, which controls the for-loop, to work like the following Python code:

iterator = iter(collection)
while True:
    try:
        x = next(iterator)
        # do something
    except StopIteration as e:
        break

Thus, the above code is the equivalent of:

for x in collection:
    # do something

For any given object, the next built-in function calls the object's __next__ "dunder" method, and the iter calls __iter__. By implementing these methods in your class, you can control the way a for-loop behaves for your custom object. Note, the above code just serves to illustrate the behavior. It is not the actual implementation. This was taken from Matt Harris' Intermediate Python Programming from the Treading on Python Series.

Upvotes: 0

UltraInstinct
UltraInstinct

Reputation: 44464

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.

Upvotes: 3

Related Questions