How can I pass an integer by reference in Python?
I want to modify the value of a variable that I am passing to the function. I have read that everything in Python is pass by value, but there has to be an easy trick. For example, in Java you could pass the reference types of Integer
, Long
, etc.
- How can I pass an integer into a function by reference?
- What are the best practices?
Advertisement
Answer
It doesn’t quite work that way in Python. Python passes references to objects. Inside your function you have an object — You’re free to mutate that object (if possible). However, integers are immutable. One workaround is to pass the integer in a container which can be mutated:
def change(x): x[0] = 3 x = [1] change(x) print x
This is ugly/clumsy at best, but you’re not going to do any better in Python. The reason is because in Python, assignment (=
) takes whatever object is the result of the right hand side and binds it to whatever is on the left hand side *(or passes it to the appropriate function).
Understanding this, we can see why there is no way to change the value of an immutable object inside a function — you can’t change any of its attributes because it’s immutable, and you can’t just assign the “variable” a new value because then you’re actually creating a new object (which is distinct from the old one) and giving it the name that the old object had in the local namespace.
Usually the workaround is to simply return the object that you want:
def multiply_by_2(x): return 2*x x = 1 x = multiply_by_2(x)
*In the first example case above, 3
actually gets passed to x.__setitem__
.