Home > Article > Backend Development > How can I modify an integer passed to a function in Python?
In Python, integers are immutable, meaning that once created, their value cannot be changed. This raises the question of how to pass an integer by reference, allowing modifications made within a function to be reflected in the original variable.
Passing a Mutable Container
While it's not possible to pass an integer by reference directly, you can pass it in a mutable container, such as a list:
def change(x): x[0] = 3 x = [1] change(x) print(x)
Output:
[3]
In this example, we create a list x containing a single element. We then pass x to the change function, which modifies the value at index 0. Since lists are mutable, this change persists even after the function returns.
Returning a New Object
Another option is to return a new object with the modified value from the function:
def multiply_by_2(x): return 2 * x x = 1 x = multiply_by_2(x)
In this case, the multiply_by_2 function returns a new object with the doubled value, which is then assigned to x. The original integer x remains unchanged.
Best Practices
When passing integers to functions, consider the following best practices:
The above is the detailed content of How can I modify an integer passed to a function in Python?. For more information, please follow other related articles on the PHP Chinese website!