What is the execution flow of the for loop in python?

squares = []  
for x in range(1, 5):
    squares.append(x)
    print(squares)

the result is

[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]

my understanding is as follows, is this correct? Or should I force an explanation?

x = 1, append (x) adds 1 to the list. At this time squares = [1]
x = 2, data 2 is added on the basis of the list squares = [1], so squares = [1,2]
is listed in turn.

PS: I know this question is very elementary, but I still hope the gods can help me with it. Thank you.


your explanation is correct


start with your code:

  

you go to understand the scope of variables, LEGB rule

Menu