Yes, they are different operators that compile to different bytecode:
>>> import dis
>>> def test1(x):
... x = x + 1
...
>>> def test2(x):
... x += 1
...
>>> dis.dis(test1)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (1)
6 BINARY_ADD
7 STORE_FAST 0 (x)
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
>>> dis.dis(test2)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (1)
6 INPLACE_ADD
7 STORE_FAST 0 (x)
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
In this case, it won't make a huge difference as int
s are immutable. In theory they could be implemented in different ways (depending on the interpreter), but that won't change the way it operates on the value.
In general, they can be implemented to do completely different things (+
being implemented by the magic method __add__()
and +=
with __iadd()__
) - in most mutable containers, for example, it makes a huge difference, if you have different names referencing the same object:
>>> x = []
>>> y = x
>>> x += [1]
>>> y
[1]
>>> x = x + [1]
>>> y
[1]
>>> x
[1, 1]
You can see that when we assign x
to y
, they both point to the same list. When we use +=
, we extend the list and both change. When we assign a new value to x
, y
still points to the original and remains unchanged.