0

Given an array nums=[3,2,1,0]

when I run this code:

i=0
nums[i],i=None,nums[i]
print(i,nums)
>>>3 [None, 2, 1, 0]

But when I change the order of value assignment

i=0
i,nums[i]=nums[i],None
print(i,nums)
>>>3 [3, 2, 1, None]

This makes me feel confused because I think the assignment happens simultaneously

Here, in my first code snippet, it runs as expected, nums[i] is set to None and i is set to old nums[i]at the same time

But in the second code snippet, it seems that i is set to 3 first, and then nums[3] is set to None.

waw waw
  • 129
  • 1
  • 4
  • 9

2 Answers2

2

The evaluation order can be found in the documentation. The relevant section would be:

expr3, expr4 = expr1, expr2

Where we have, in order:

  • expr1: nums[i] evaluated to 3
  • expr2: None
  • expr3: i set to the result of expr1
  • expr4: nums[i] where the i used is set in expr3.

That order of operations, specifically in this case where our fourth expression is based on our third, is what is messing it up.

NGilbert
  • 485
  • 6
  • 12
  • Neat, I would've picked that as implementation detail rather than canonically documented! TIL! – Jiří Baum Sep 01 '21 at 14:59
  • BTW, for further experimentation, we could define an object with properties (or overriding `[]`) then `print` when each of the getters and setters is called; however, the documentation is clear enough – Jiří Baum Sep 01 '21 at 15:02
0

I recently learned that the assignments work left to right.

Although, first, the expression on the right hand side of the = is evaluated, then the items on the left hand side are assigned, one-at-a-time.

This mean that in the second snippet you will have:

i = nums[i]     #  first
nums[i] = None  # second

It looks like, here, that i is modified before the second assignment takes place.

quamrana
  • 37,849
  • 12
  • 53
  • 71