a = [1, 2, 3] a[-1] += a.pop()
This results in [1, 6]
.
a = [1, 2, 3] a[0] += a.pop()
This results in [4, 2]
. What order of evaluation gives these two results?
List pop in Python is a pre-defined, in-built function that removes an item at the specified index from the list. You can also use pop in Python without mentioning the index value. In such cases, the pop() function will remove the last element of the list.
The pop() method removes the item at the given index from the list and returns the removed item.
The pop() method removes the element at the specified position.
Python list pop() is an inbuilt function in Python that removes and returns the last value from the List or the given index value.
RHS first and then LHS. And at any side, the evaluation order is left to right.
a[-1] += a.pop()
is same as, a[-1] = a[-1] + a.pop()
a = [1,2,3] a[-1] = a[-1] + a.pop() # a = [1, 6]
See how the behavior changes when we change the order of the operations at RHS,
a = [1,2,3] a[-1] = a.pop() + a[-1] # a = [1, 5]
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With