Home >Backend Development >Python Tutorial >Is Python Pass-by-Value or Pass-by-Reference, and How Can I Achieve Pass-by-Reference Behavior?
While writing a class for testing, you've noticed that parameters in Python seem to be passed by value rather than by reference. This article will clarify whether your assumption is correct and guide you in implementing pass-by-reference in Python.
In Python, arguments are passed by reference, which means that a reference to the object is passed to the function. However, this reference is passed by value. This behavior arises due to the differentiation between mutable and immutable data types.
Consider the following example:
def try_to_change_list_contents(the_list): the_list.append('four') outer_list = ['one', 'two', 'three'] try_to_change_list_contents(outer_list) print(outer_list)
Since lists are mutable, the the_list parameter is a reference to the outer_list object. By appending 'four' to the_list, the outer_list is also modified.
In contrast, consider this example with strings:
def try_to_change_string(my_string): my_string = 'Changed' outer_string = 'Original' try_to_change_string(outer_string) print(outer_string)
Despite changing the my_string variable within the function, the outer_string remains unchanged. This occurs because strings are immutable and cannot be modified in place.
To mimic pass-by-reference, where the original variable is modified, there are a few options:
1. Returning a New Value: The function can return a new value, which can be assigned to the original variable outside the function.
2. Modifying the Object's Attribute: If the variable is an object, the function can modify one of its attributes, which will be reflected in the original object.
3. Using Lists or Wrappers: You can wrap the variable in a list and pass the list to the function. Modifying the list will affect the original variable.
By understanding the pass-by-value and reference mechanisms, you can effectively modify variables in Python as desired.
The above is the detailed content of Is Python Pass-by-Value or Pass-by-Reference, and How Can I Achieve Pass-by-Reference Behavior?. For more information, please follow other related articles on the PHP Chinese website!