Surprise from Python +=
Thanks to the augmented arithmetic assignments
methods,
x += y
is not equivalent to x = x + y
.
First of all, some backgrounds.
Conceptually a Python variable is different from a C variable:
While a C variable is just a name of a memory location, which you store values,
a Python variable is actually a name of a value (we say the variable is bound to that value).
So in C, =
is an assignment in the sense that you copy the value to the memory location of the variable.
On the contrary, in Python, =
is a re-binding in the sense that you bind the variable to a new value.
In other words, a Python variable is like a C pointer,
and “assign to” a Python variable is like making it point to another memory location.
(Note that in C, a variable occupies a memory location, but in Python, it is value that occupies a memory location.)
Let’s put the idea into practice:
Here comes the surprise from +=
:
So be careful about the surprise from +=
.