>>> 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)
为什么同一操作有不同的行为.
a = b + c表示"设置a为b加号c".a += b意思是"添加b到a".第一个,b + c只是意味着" b加c"; 它们被加在一起形成一个代表其想法的新列表b + c.但在第二,b被添加a; b由此改变了.
这种概念差异反映在所谓的不同方法中; __add__对于前者和__iadd__后者.