为什么+运算符创建一个新列表但+ = not

tar*_*967 -1 python list

>>> List1 = [1,2,3,4,5]  #Normal List
>>> list2 = list1        
>>> list1 is list2       #list2 is also pointing to the same location as list1
True
Run Code Online (Sandbox Code Playgroud)

但是当我们使用+运算符时,它会创建一个新列表

>>> list2 = list2 + [5]  #adding a list to list2
>>> list1 is list2       #list1 is not pointing to the same location as list2
False
>>> list2                #list2 is modified
[1, 2, 3, 4, 5, 5]
>>> list1                #but list1 is same as before
[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

但是当我们使用+ =运算符时,它不会创建新的列表

>>> list2 += [5]         #adding a list to list2
>>> list1 is list2       #list1 is pointing to the same location as list2
True
>>> list2                #list2 is modified
[1, 2, 3, 4, 5, 5]
>>> list1                #list1 is also modified
[1, 2, 3, 4, 5, 5]
Run Code Online (Sandbox Code Playgroud)

为什么同一操作有不同的行为.

wiz*_*zz4 7

a = b + c表示"设置ab加号c".a += b意思是"添加ba".第一个,b + c只是意味着" bc"; 它们被加在一起形成一个代表其想法的新列表b + c.但在第二,b被添加a; b由此改变了.

这种概念差异反映在所谓的不同方法中; __add__对于前者和__iadd__后者.