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

时间:2018-07-07 10:52:41

标签: 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

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

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

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

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

为什么同一操作会有不同的行为。

1 个答案:

答案 0 :(得分:7)

a = b + c的意思是“将a设置为bc”。 a += b的意思是“将b添加到a”。对于第一个,b + c仅表示“ bc”;将它们加在一起形成代表b + c想法的新列表。但是第二步是将b添加到a中。 b对此进行了更改。

这种概念上的差异体现在所称的不同方法中;前者__add__,后者__iadd__