The difference between "i + = i and i = i + i" in Python: (reference, memory, variable parameters, immutable parameters)

“I + = i + i = i + i” in Python

1. Changes in data memory when "i + = i" is executed

When num + = num is executed, the memory space originally referenced by num changes according to whether the data type of the parameters stored in the space is variable. *** Variable parameter data types *** are: list, dictionary ; *** The types of immutable parameters *** are: numbers, strings, tuples.

#代码1
a=100
def test(num):
    num+=num
    print("in----test----  num="+str(num))

test(a)
print(a)

When a = 100, 100 is an immutable type, so when the num in the function points to 100 and needs to be changed,
the 100 in num cannot be changed directly, so the first num in the function test is essentially a local variable,
which points to a The new "sum value" corresponds to the memory space, so the output result is num: 200, a: 100, and
the value of the global variable a has not changed.

#代码2
a=[100]
def test(num):
    num+=num
    print("in----test----  num="+str(num))

test(a)
print(a)

When a = [100], A points to a memory space of variable type, so when sum + = sum is executed,
the value in the memory space changes, the list content is merged, the reference of a does not change, and the
output result is num: [ 100,100], a: [100,100], it can be seen that the value of the global variable a has also changed.

Therefore, when using functions to calculate global variables, you should pay attention to whether the global variables are variable types.

2. Changes in data memory when "i = i + i" is executed

When num = num + num when executed, num value points to a record of the original memory space calculated by the expression results ofNewMemory space.

#代码3
a=[100]
def test(num):
    num=num+num
    print("in----test----  num="+str(num))

test(a)  #[100,100]
print(a) #[100]

Therefore, after the function runs, even if the global variable is a variable parameter type, the value in the memory space referenced by the global variable a has not changed.

Published 8 original articles · won 16 · 40,000+ views

Guess you like

Origin blog.csdn.net/knkn123/article/details/82973187
I
"I"
I: