Home >Backend Development >Python Tutorial >How Does Python Handle Pass-by-Reference and Pass-by-Value?
In Python, passing arguments to functions is done by reference, meaning that the passed parameter is a reference to the actual object. However, it's important to understand the distinction between passing a reference by value versus actually passing by reference.
In Python, parameters are passed by value, which means a copy of the object is assigned to the parameter within the function. This has two implications:
Although true pass-by-reference is not directly supported in Python, there are several techniques to simulate it:
The following code demonstrates pass-by-reference with a mutable (list) and an immutable (string):
# Mutable List def modify_list(the_list): the_list.append('four') outer_list = ['one', 'two', 'three'] print("Before: ", outer_list) modify_list(outer_list) print("After: ", outer_list) # Immutable String def modify_string(the_string): the_string = 'In a kingdom by the sea' outer_string = 'It was many and many a year ago' print("Before: ", outer_string) modify_string(outer_string) print("After: ", outer_string)
Output:
Before: ['one', 'two', 'three'] After: ['one', 'two', 'three', 'four'] Before: It was many and many a year ago After: It was many and many a year ago
As seen in the output, the list is modified successfully (pass-by-reference), while the string remains unchanged (pass-by-value).
The above is the detailed content of How Does Python Handle Pass-by-Reference and Pass-by-Value?. For more information, please follow other related articles on the PHP Chinese website!