Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the order of evaluation in python when using pop(), list[-1] and +=?

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?

like image 606
graffe Avatar asked Mar 13 '17 10:03

graffe


People also ask

What does Pop 1 do in Python?

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.

What does the pop () list method do?

The pop() method removes the item at the given index from the list and returns the removed item.

What does Pop () mean in Python?

The pop() method removes the element at the specified position.

What is the usage of pop () in list in Python?

Python list pop() is an inbuilt function in Python that removes and returns the last value from the List or the given index value.


2 Answers

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] 
like image 62
Fallen Avatar answered Oct 13 '22 00:10

Fallen


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() returns 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.

like image 23
Chris_Rands Avatar answered Oct 13 '22 01:10

Chris_Rands