First code:
# -*- coding:gb2312 -*- a = [100] def test(num): num += num #第一段代码 print(num) test(a) print(a)
Results of the:
Second code:
# -*- coding:gb2312 -*- a = [100] def test(num): num = num + num #这个地方改了一下 print(num) test(a) print(a)
Results of the:
My question:
Shouldn't num = num be directly equivalent to mun = num num?
Why are the calculated results different? What is going on
You can try to do something like this,
The memory address allocated to the variable can be obtained through the id() function. Through experiments, it was found that the variable address using
+
has changed, which is what you said num+=num and num=num+numare not equivalent.However, when you do the following sexy operations, you will find yourself slapped in the face
The assigned address seems to keep changing.
The reason is that data structures in Python are divided into mutable and immutable.
For variable types, = and += are obviously different, as shown in the list above:
+ represents a connection operation, += represents appending
For immutable types, = and += are the same operations, such as the tuple above
The essence of variable types and immutable types lies in whether the memory space is variable~
The first thing to notice is the difference
You can see that the methods called are different, they are __add__, __iadd__
The addition operator will calculate a new object to assign to num
The incremental assignment operator modifies the original reference
Reference here: https://stackoverflow.com/que...
Remember that arguments are passed by assignment in Python.
In Python, assignment is used to pass parameters, not reference, so when you pass a to a function, you pass the value of a, not a itself. If you want to change a itself, you need to use return to pass the value back
Result:
In python, a=a+b means first creating a new object and letting variable a refer to this object. a+=b changes thevalueof the object referenced by a into the value of a+b