How do you pass a string by reference in python?
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Pass by Reference in Python: Best Practices Show
After gaining some familiarity with Python, you may notice cases in which your functions don’t modify arguments in place as you might expect, especially if you’re familiar with other programming languages. Some languages handle function arguments as references to existing variables, which is known as pass by reference. Other languages handle them as independent values, an approach known as pass by value. If you’re an intermediate Python programmer who wishes to understand Python’s peculiar way of handling function arguments, then this tutorial is for you. You’ll implement real use cases of pass-by-reference constructs in Python and learn several best practices to avoid pitfalls with your function arguments. In this tutorial, you’ll learn:
Defining Pass by ReferenceBefore you dive into the technical details of passing by reference, it’s helpful to take a closer look at the term itself by breaking it down into components:
Since you’re giving the function a reference to an existing variable, all operations performed on this reference will directly affect the variable to which it refers. Let’s look at some examples of how this works in practice. Below, you’ll see how to pass variables by reference in C#. Note the use of the
As you can see, the Python has no >>>
In this case, the Not quite. Python passes arguments neither by reference nor by value, but by assignment. Below, you’ll quickly explore the details of passing by value and passing by reference before looking more closely at Python’s approach. After that, you’ll walk through some best practices for achieving the equivalent of passing by reference in Python. Contrasting Pass by Reference and Pass by ValueWhen you pass function arguments by reference, those arguments are only references to existing values. In contrast, when you pass arguments by value, those arguments become independent copies of the original values. Let’s revisit the C# example, this time without using the
Here, you can see that Python’s built-in
In the below example, note that the address of >>>
The fact that the initial addresses of Before you learn the details of how Python handles arguments, let’s take a look at some practical use cases of passing by reference. Using Pass by Reference ConstructsPassing variables by reference is one of several strategies you can use to implement certain programming patterns. While it’s seldom necessary, passing by reference can be a useful tool. In this section, you’ll look at three of the most common patterns for which passing by reference is a practical approach. You’ll then see how you can implement each of these patterns with Python. Avoiding Duplicate ObjectsAs you’ve seen, passing a variable by value will cause a copy of that value to be created and stored in memory. In languages that default to passing by value, you may find performance benefits from passing the variable by reference instead, especially when the variable holds a lot of data. This will be more apparent when your code is running on resource-constrained machines. In Python, however, this is never a problem. You’ll see why in the next section. Returning Multiple ValuesOne of the most common applications of passing by reference is to create a function that alters the value of the reference parameters while returning a distinct value. You can modify your pass-by-reference C# example to illustrate this technique:
In the example above, >>>
In essence, reference parameters in C# allow the function not only to return a value but also to operate on additional parameters. This is equivalent to returning multiple values! Luckily, Python already supports returning multiple values. Strictly speaking, a Python function that returns multiple values actually returns a tuple containing each value: >>>
As you can see, to return multiple values, you can simply use the Armed with this technique, you can change the >>>
That still doesn’t look right. Although To clean up your output and get the desired results, you’ll have to reassign your >>>
Now, after reassigning each variable with a call to Assigning return values to variables is the best way to achieve the same results as passing by reference in Python. You’ll learn why, along with some additional methods, in the section on best practices. Creating Conditional Multiple-Return FunctionsThis is a specific use case of returning multiple values in which the function can be used in a conditional statement and has additional side effects like modifying an external variable that was passed in as an argument. Consider the standard Int32.TryParse function in C#, which returns a Boolean and operates on a reference to an integer argument at the same time:
This function attempts to convert a
You can see this in practice in the following example, which attempts to convert a number of different strings:
The above code, which attempts to convert differently formatted strings into integers via
To implement a similar function in Python, you could use multiple return values as you’ve seen previously:
This However, using this function is a little clunky because you need to unpack the return values with every call. This means you can’t use the function within an >>>
Even
though it generally works by returning multiple values, You can take advantage of Python’s flexibility and simplify the function to return a single value of different types depending on whether the conversion succeeds:
With the ability for Python functions to return different data types, you can now use this function within a conditional statement. But how? Wouldn’t you have to call the function first, assigning its return value, and then check the value itself? By taking advantage of Python’s flexibility in object types, as well as the new assignment expressions in Python 3.8, you can call this simplified function within a conditional >>>
Wow! This Python version of With a little ingenuity, you’ve replicated a specific and useful pass-by-reference pattern without actually passing arguments by reference. In fact, you are yet again assigning return values when using the assignment expression
operator( So far, you’ve learned what passing by reference means, how it differs from passing by value, and how Python’s approach is different from both. Now you’re ready to take a closer look at how Python handles function arguments! Passing Arguments in PythonPython passes arguments by assignment. That is, when you call a Python function, each function argument becomes a variable to which the passed value is assigned. Therefore, you can learn important details about how Python handles function arguments by understanding how the assignment mechanism itself works, even outside functions. Understanding Assignment in PythonPython’s language reference for assignment statements provides the following details:
All Python objects are implemented in a particular structure. One of the properties of this structure is a counter that keeps track of how many names have been bound to this object. Let’s stick to the
Now here’s what happens if you reassign
Python allows you to obtain the reference counts for arbitrary values with the function
This script will show the reference counts for each value prior to assignment, after assignment, and after reassignment:
These results illustrate the relationship between identifiers (variable names) and Python objects that represent distinct values. When you assign multiple variables to the same value, Python increments the reference counter for the existing object and updates the current namespace rather than creating duplicate objects in memory. In the next section, you’ll build upon your current understanding of assignment operations by exploring how Python handles function arguments. Exploring Function ArgumentsFunction arguments in Python are local variables. What does that mean? Local is one of Python’s scopes. These scopes are represented by the namespace dictionaries mentioned in the previous section. You can use Upon execution, each function has its own local namespace: >>>
Using >>>
You can also use >>>
The above script outputs reference counts for That’s because, in addition to By examining namespaces and reference counts inside functions, you can see that function arguments work exactly like assignments: Python creates bindings in the function’s local namespace between identifiers and Python objects that represent argument values. Each of these bindings increments the object’s reference counter. Now you can see how Python passes arguments by assignment! Replicating Pass by Reference With PythonHaving examined namespaces in the previous section, you may be asking why >>>
Using the
Contrast the previous example with the following, which explicitly returns a value: >>>
Much better! You avoid all potential issues with global variables, and by requiring an argument, you make your function clearer. Despite being neither a pass-by-reference language nor a pass-by-value language, Python suffers no shortcomings in that regard. Its flexibility more than meets the challenge. Best Practice: Return and ReassignYou’ve already touched on returning values from the function and reassigning them to a variable. For functions that operate on a single value, returning the value is much clearer than using a reference. Furthermore, since Python already uses pointers behind the scenes, there would be no additional performance benefits even if it were able to pass arguments by reference. Aim to write single-purpose functions that return one value, then (re)assign that value to variables, as in the following example:
Returning and assigning values also makes your intention explicit and your code easier to understand and test. For functions that operate on multiple values, you’ve already seen that Python is capable of returning a tuple of values. You even surpassed the elegance of Int32.TryParse() in C# thanks to Python’s flexibility! If you need to operate on multiple values, then you can write single-purpose functions that return multiple values, then (re)assign those values to variables. Here’s an example:
When calling a function that returns multiple values, you can assign multiple variables at the same time. Best Practice: Use Object AttributesObject attributes have their own place in Python’s assignment strategy. Python’s language reference for assignment statements states that if the target is an object’s attribute that supports assignment, then the object will be asked to perform the assignment on that attribute. If you pass the object as an argument to a function, then its attributes can be modified in place. Write functions that accept objects with attributes, then operate directly on those attributes, as in the following example: >>>
Note that It’s worth repeating that you should make sure the attribute supports assignment! Here’s the same example with >>>
Attempts to modify attributes that don’t allow modification result in an Additionally, you should be mindful of class attributes. They will remain unchanged, and an instance attribute will be created and modified: >>>
Since class attributes remain unchanged when modified through a class instance, you’ll need to remember to reference the instance attribute. Best Practice: Use Dictionaries and ListsDictionaries in Python are a different object type than all other built-in types. They’re referred to as mapping types. Python’s documentation on mapping types provides some insight into the term:
This tutorial doesn’t cover how to implement a custom mapping type, but you can replicate pass by reference using the humble dictionary. Here’s an example using a function that operates directly on dictionary elements: >>>
Since you’re reassigning a value to a dictionary key, operating on dictionary elements is still a form of assignment. With dictionaries, you get the added practicality of accessing the modified value through the same dictionary object. While lists aren’t mapping types, you can use them in a similar way to dictionaries because of two important characteristics: subscriptability and mutability. These characteristics are worthy of a little more explanation, but let’s first take a look at best practices for mimicking pass by reference using Python lists. To replicate pass by reference using lists, write a function that operates directly on list elements: >>>
Since you’re reassigning a value to an element within the list, operating on list elements is still a form of assignment. Similar to dictionaries, lists allow you to access the modified value through the same list object. Now let’s explore subscriptability. An object is subscriptable when a subset of its structure can be accessed by index positions: >>>
Lists, tuples, and strings are subscriptable, but sets are not. Attempting to access an element of an object that isn’t subscriptable will raise a Mutability is a broader topic requiring additional exploration and documentation reference. To keep things short, an object is mutable if its structure can be changed in place rather than requiring reassignment: >>>
Lists and sets are mutable, as are dictionaries and other mapping types. Strings and tuples are not mutable. Attempting to modify an element
of an immutable object will raise a ConclusionPython works differently from languages that support passing arguments by reference or by value. Function arguments become local variables assigned to each value that was passed to the function. But this doesn’t prevent you from achieving the same results you’d expect when passing arguments by reference in other languages. In this tutorial, you learned:
You also learned some additional best practices for replicating pass-by-reference constructs in Python. You can use this knowledge to implement patterns that have traditionally required support for passing by reference. To continue your Python journey, I encourage you to dive deeper into some of the related topics that you’ve encountered here, such as mutability, assignment expressions, and Python namespaces and scope. Stay curious, and see you next time! Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Pass by Reference in Python: Best Practices How do you pass by reference in Python?If a Python newcomer wanted to know about passing by ref/val, then the takeaway from this answer is: 1- You can use the reference that a function receives as its arguments, to modify the 'outside' value of a variable, as long as you don't reassign the parameter to refer to a new object.
How do you pass a string as a reference?First, we have the function definition “DisplayString,” where a constant string reference is passed. The constant strings are defined and initialized in the main function as “str1” and “str2”. After that, pass these constant strings to the function “InputString”.
How do you pass a string variable in Python?Python: Add Variable to String & Print Using 4 Methods. Method #1: using String concatenation.. Method #2: using the "%" operator.. Method #3: using the format() function.. Method #4: using f-string.. Conclusion.. Is Python pass by value or pass by reference?The two most widely known and easy to understand approaches to parameter passing amongst programming languages are pass-by-reference and pass-by-value. Unfortunately, Python is “pass-by-object-reference”, of which it is often said: “Object references are passed by value.”
|