Python pass variable to function by reference
Arguments are passed by assignment. The rationale behind this is twofold: Show
So:
To make it even more clear, let's have some examples. List - a mutable typeLet's try to modify the list that was passed to a method:
Output:
Since the parameter passed in is a reference to Now let's see what happens when we try to change the reference that was passed in as a parameter:
Output:
Since the
String - an immutable typeIt's immutable, so there's nothing we can do to change the contents of the string Now, let's try to change the reference
Output:
Again, since the I hope this clears things up a little. EDIT: It's been noted that this doesn't answer the question that @David originally asked, "Is there something I can do to pass the variable by actual reference?". Let's work on that. How do we get around this?As @Andrea's answer shows, you could return the new value. This doesn't change the way things are passed in, but does let you get the information you want back out:
If you really wanted to avoid using a return value, you could create a class to hold your value and pass it into the function or use an existing class, like a list:
Although this seems a little cumbersome. Can I pass a variable by reference in Python?Python passes arguments neither by reference nor by value, but by assignment.
How do you pass a variable to a function in Python?Use function syntax to pass variables to a function
Use the syntax function_name(value1, value2, value3) to pass value1 , value2 , and value3 to function_name . The number of values passed should match the number of parameter names specified in the function definition.
Can you pass a variable by reference?Pass by reference is something that C++ developers use to allow a function to modify a variable without having to create a copy of it. To pass a variable by reference, we have to declare function parameters as references and not normal variables.
Is Python pass by value or pass by reference?Python always uses pass-by-reference values. There isn't any exception. Any variable assignment means copying the reference value.
|