the difference between i += 1 and i = i + 1

今天朋友碰到了问题

1
2
3
4
5
6
7
8
9
l = []
lst = []
lst.append(l)
l += [1]
# lst = [1]
l = l + [2]
# lst = [1]
l += [3]
# lst = [3]

为什么lst里面的l值通过 l += [1]可以改变, 而l = l + [1]就没法影响lst里面的值呢?

解决

+= 是对原本的实例做加1运算, l = l + [1]是对l + [1]之后重新把值赋给叫l的变量(和原来的l不同)。

The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1.

Just for completeness:

x += y is not always doing an in-place operation, there are (at least) three exceptions:

If x doesn’t implement an iadd method then the x += y statement is just a shorthand for x = x + y. This would be the case if x was something like an int.

If iadd returns NotImplemented, Python falls back to x = x + y.

The iadd method could theoretically be implemented to not work in place. It’d be really weird to do that, though.

转自:
What is the difference between i = i + 1 and i += 1 in a ‘for’ loop? [duplicate]