Search code examples
pythonlistoperator-precedenceindices

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?


Solution

  • 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]