Why does python list L += x behaves differently than L = L + x?
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 11 | ls = [1,2,3] id(ls) output: 4448249184 # (a) ls += [4] id(ls) output: 4448249184 # (b) ls = ls + [4] id(ls) output: 4448208584 # (c) |
为什么(a)和(b)相同,但(b)和(c)不同?
使用
These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self).
使用
也可参见清单
列表案例中的增广赋值是不同的。它不是像整数那样的实际赋值,因此
1 | a += b |
等于
1 | a = a+b |
而在列表的情况下,它的操作方式如下:
1 | list += x |
是:
1 | list.extends(x) |