Why does multiple list values assignments in one line not change the corresponding value in the list?

Viewed 53

In the Computer Science test, I was asked to determine the output of this code:

L = [12, 3, 1, 5, 13, 18, 85, 10, 2, 74, 1, 12, 3]
i = 1
while i < len(L):
    L[i-1], L[i] = L[i], L[i-1]
    i += 2
print(L)

The code looks very simple, but there is something that confused me and made my answer wrong and it's the code in line 4.

Let's take an example so that you get how I understood that line of code : let's take i = 1.
Then L[0], L[1] = L[1], L[0]

This means that L[0] = L[1] (L[0] would be then 3) and L[1] = L[0] (here I thought that this assignment is useless as L[0] is now equal to L[1] = 3)

However, when I came home and executed the code with my laptop, I realized I was wrong but I still don't get my mistake.

Btw, I guess it's maybe the line 4 syntax (2 assignments in only one line)

2 Answers

So, this is actually a feature of python called multiple assignment that is sometimes difficult to grasp if you are coming from other languages. This is how it works.

Eg. a, b = b, a

This code will actually swap the elements. I will give a simple intuitive explanation, and then a more technical one.

  1. The RHS is first evaluated, and then values are assigned respectively to variables (labels) on the LHS.
  2. So you can actually define a tuple (a,b) as a,b in python, the parentheses are just for better readability. So your RHS is a tuple that is unpacked and each element is assigned respectively to each label on the LHS. So all the following code snippets are equivalent.
a, b = b, a
a, b = (b, a)
a, b = [b, a]

Refer to this SO post for a more detailed explanation.

NOTE: The notion of variables in python is very very different from other languages where they are containers of a certain type to store values of that type. In python, labels is a more correct term than variables because you are just labeling an object with this name, and the object can be of any datatype. So to understand this code, you are not actually swapping values when you do a,b = b,a, you are swapping labels.
So, python first looks up the values that labels b and a point to on the RHS, puts those values there, and then it just gives these values new labels.

I hope that clears it up!

Related