Python list, in numpy array
a = a + b
ʻA + = b` (called cumulative assignment)
It should be noted that the behavior of is different.
In Python cumulative assignment, perform in-place operations if possible. That is, if the contents of the object can be changed, a new object is not created.
Therefore, it is important whether the object is mutable or immutable. Numeric types are immutable objects, and lists are mutable objects.
There is an id function as a built-in function of Python. You can get the identification value of the object by using the id function. The identification value is guaranteed to be unique and constant for the life of the object. So, I will explain the difference between the two using this id function.
First of all, from ʻa + = 1`.
test1.py
a = 1
print (id(a))
a += 1
print (id(a))
test1.py execution result
1663828464
1663828496
It can be seen that the identification value of a has changed.
In Python, numeric types are immutable objects,
This is because the reference destination of a changes depending on the processing of ʻa + = 1. Next, let's look at ʻa = a + 1
.
test2.py
a = 1
print (id(a))
a = a + 1
print (id(a))
test2.py execution result
1656226288
1656226320
After all, it can be seen that the identification value of a has changed. There should be no problem so far.
This is the main subject.
test3.py
a = [0,1,2]
b = [2,3,4]
print (id(a))
a = a + b
print (id(a))
test3.py execution result
53560776
53560200
The identification value of a has changed. next,
test4.py
a = [0,1,2]
b = [2,3,4]
print (id(a))
a += b
print (id(a))
test4.py execution result
53560008
53560008
This time, the identification value of a has not changed.
I will omit the experimental results for the numpy array because it will be tedious. The result is similar to a regular list. The official numpy tutorial also states:
Arithmetic operators on arrays apply elementwise. A new array is created and filled with the result.
Some operations, such as += and *=, act in place to modify an existing array rather than create a new one.
a = a + b
a += b
It should be noted that the description such as is not always equivalent.
Recommended Posts