0

As we all know, for Python, we could easily assignment multiple variables in one line. But here I encounter a strange situation. Say we have a list:

x = [1, 2, 3, 4]

And then, we do

x[0], x[x[0]] = 2, 1

Finally, we would get

x = [2, 2, 3, 4]

instead of

x = [2, 1, 3, 4]

Could anyone explain what is going wrong here? How would python implement the multiple variables assignment in one line?

Thanks in advance.

  • Please also check this: https://stackoverflow.com/questions/8725673/multiple-assignment-and-evaluation-order-in-python – supl Nov 22 '18 at 05:34
  • So basically, Python will evaluate right-hand side of the statement (only read, no contention), and then it will assign to variables on the left-hand side from left to right. Thanks all!! – UserNotFound Nov 22 '18 at 05:42

2 Answers2

1

The resulting list is not [2, 2, 3, 4], it's [2, 2, 1, 4]. x[0] is assigned the value 2, then x[x[0]] becomes x[2] and is assigned the value 1

M.G
  • 440
  • 1
  • 3
  • 10
0

What happens here is, python first executes your first instruction . x[0]= 2

So after 1st execution, x=[2,2,3,4]

Then it executes the 2nd one. So it changes the value of x[2]

after 2nd execution, x=[2,2,1,4]

and gives the result as [2, 2, 1, 4]

Sandesh34
  • 279
  • 1
  • 2
  • 14