How do the variables in a `for` statement get defined?

Question:

I came across code like this:

s1 = "mit u rock"
s2 = "i rule mit"
if len(s1) == len(s2):
    for char1 in s1:
        for char2 in s2:
            if char1 == char2:
                print("common letter")
                break

I notice there are no previous defines for the variable like char1 or char2, so how does this work? I think it might be some “keyword for a variable” that Python understands. If so, could you tell me what’s it called, and what are other common variables like this?

Asked By: trang nguyen

||

Answers:

What that for loop does is loop over s1. For every iteration it assigns an element of iterable container s1 to variable char1.

Therefore, on the first iteration of the loop for char1 in s1, char1 will have the string value 'm', on the second iteration string value 'i'.

Note that even after the loop has finished executing, char1 will still have a value assigned (the last iteration means it will have value 'k').

What your iterating over doesn’t have to be a string, it can be any object that defines __iter__ and __next__ methods. So some examples are a list [1,2,3] or a generator like what is returned by function invokation range(5).

Answered By: DBedrenko
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.