Python function parameters: pass by value and pass by reference

Firstly, let me briefly explain the difference between passing by value and by reference in Python:

Passing by value parameterrefers to the practice of replacing a function parameter with the value of a variable


Passing by reference parameterrefers to maintaining a link (reference) to a variable in the code that calls this function

Function called by value

def double(arg):
	print('Before:', arg)
	arg = arg * 2
	print('After:', arg)
num = 10
double(num)
print('num:', num)
saying = 'Hello'
double(saying)
print('saying:', saying)

Run the above code and the output result is as follows:

Before: Hello.

Analysis
Each call confirms that the value passed as a parameter has changed in the function code group, but the value printed outside the function remains unchanged.


Function called by reference

def change(arg):
	pring('Before:', arg)
	arg.append('More data')
	print('After:', arg)
numbers = [42, 256, 16]
change(numbers)
print(numbers)

Run the above code and the output result is as follows:

Before: [42, 256, 16]
After: [42, 256, 16, 'More data']
Numbers: [42, 256, 16, 'More data'].

Analysis
This time, not only did the parameter values in the function change, but also the values printed out from the outside of the function changed Does Python function parameter support passing by value or by reference

Depending on the specific situation, Python's function parameterssupport bothand Transfer by value AlsoSupport Pass by reference

In fact, the interpreter will check the type of the value indicated by the object reference (memory address). If the variable indicates amutablevalue, it will call semantics by reference. If the type of the indicated data isimmutable, it will apply semantics by value.

The list dictionary collection always passes functions by reference, and any changes to the variable data structure in the function code group will Reflected in the calling code

The string integer tuple
is always passed into the function by value, and any modifications to variables in the function are private to the function, Will not be reflected in the calling code

Related articles