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

后端 未结 5 870
感情败类
感情败类 2021-02-05 00:48
a = [1, 2, 3]
a[-1] += a.pop()

This results in [1, 6].

a = [1, 2, 3]
a[0] += a.pop()

This results in

5条回答
  •  太阳男子
    2021-02-05 01:11

    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]
    

提交回复
热议问题