a = [1, 2, 3]
a[-1] += a.pop()
This results in [1, 6]
.
a = [1, 2, 3]
a[0] += a.pop()
This results in
The key insight is that a[-1] += a.pop()
is syntactic sugar for a[-1] = a[-1] + a.pop()
. This holds true because +=
is being applied to an immutable object (an int
here) rather than a mutable object (relevant question here).
The right hand side (RHS) is evaluated first. On the RHS: equivalent syntax is a[-1] + a.pop()
. First, a[-1]
gets the last value 3
. Second, a.pop()
return
s 3
.
3
+ 3
is 6
.
On the Left hand side (LHS), a
is now [1,2]
due to the in-place mutation already applied by list.pop()
and so the value of a[-1]
is changed from 2
to 6
.