pythonloopsvariable-assignment

Is it possible to have a variable inside a for loop named exactly as the variable in the loop header?


I am a little confused regarding the assignment statement inside the code block of a for loop.

EXAMPLE CODE:

my_list = ['1', '2', '3', '4']

my_new_list = []
for element in my_list:
    element = int(element) ** 2
    my_new_list.append(str(element))
print(my_new_list)

Basically, I'm having trouble understanding this assignment statement from the code above: element = int(element) ** 2

I know that the expression on the right side of the = gets evaluated first and then it is assigned to the variable on the left side of the =. But I've learned that by using the for loop, the variable in loop header (here being element) gets assigned each value of the iterable (here being my_list) step by step.

So my mind basically sees these statements (which I know there are syntactically wrong, as you cannot assign a value to a string literal):

'1' = int('1') ** 2

'2' = int('2') ** 2

'3' = int('3') ** 2

'4' = int('4') ** 2

However, when I run the above code through Python Visualizer it shows me that everything is fine and that the variable element gets assigned the values 1, 4, 9 and 16 respectively.

How is this possible? Is there an exception for this in Python when using for loops?


Solution

  • There's nothing special about the loop. The first thing each iteration does is assign a value from my_list to the variable element. You then simply assign a new value to element, based on the old value. When the iteration completes, the loop again assigns another value from my_list to element.

    Unrolling the loop

    my_new_list = []
    for element in my_list:
        element = int(element) ** 2
        my_new_list.append(str(element))
    

    would give you something like

    my_new_list = []
    itr = iter(my_list)
    element = next(itr)  # '1'
    element = int(element) ** 2
    my_new_list.append(str(element))
    element = next(itr)  # '2'
    element = int(element) ** 2
    my_new_list.append(str(element))
    element = next(itr)  # '3'
    # etc
    

    You're never assigning "to" a str value; you're just replacing the str value previously held by element with an int value.