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

后端 未结 5 996
感情败类
感情败类 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条回答
  •  萌比男神i
    2021-02-05 01:31

    For you specific example

    a[-1] += a.pop() #is the same as 
    a[-1] = a[-1] + a.pop() # a[-1] = 3 + 3
    

    Order:

    1. evaluate a[-1] after =
    2. pop(), decreasing the length of a
    3. addition
    4. assignment

    The thing is, that a[-1] becomes the value of a[1] (was a[2]) after the pop(), but this happens before the assignment.

    a[0] = a[0] + a.pop() 
    

    Works as expected

    1. evaluate a[0] after =
    2. pop()
    3. addition
    4. assignment

    This example shows, why you shouldn't manipulate a list while working on it (commonly said for loops). Always work on copys in this case.

提交回复
热议问题