Python: How do I pass a string by reference?

Python does pass a string by reference. Notice that two strings with the same content are considered identical:

a = 'hello'
b = 'hello'
a is b        # True

Since when b is assigned by a value, and the value already exists in memory, it uses the same reference of the string. Notice another fact, that if the string was dynamically created, meaning being created with string operations (i.e concatenation), the new variable will reference a new instance of the same string:

c = 'hello'
d = 'he'
d += 'llo'
c is d        # False

That being said, creating a new string will allocate a new string in memory and returning a reference for the new string, but using a currently created string will reuse the same string instance. Therefore, passing a string as a function parameter will pass it by reference, or in other words, will pass the address in memory of the string.

And now to the point you were looking for- if you change the string inside the function, the string outside of the function will remain the same, and that stems from string immutability. Changing a string means allocating a new string in memory.

a = 'a'
b = a    # b will hold a reference to string a
a += 'a'
a is b   # False

Bottom line:

You cannot really change a string. The same as for maybe every other programming language (but don't quote me). When you pass the string as an argument, you pass a reference. When you change it's value, you change the variable to point to another place in memory. But when you change a variable's reference, other variables that points to the same address will naturally keep the old value (reference) they held. Wish the explanation was clear enough


Python does not make copies of objects (this includes strings) passed to functions:

>>> def foo(s):
...     return id(s)
...
>>> x = 'blah'
>>> id(x) == foo(x)
True

If you need to "modify" a string in a function, return the new string and assign it back to the original name:

>>> def bar(s):
...     return s + '!'
...
>>> x = 'blah'
>>> x = bar(x)
>>> x
'blah!'

Unfortunately, this can be very inefficient when making small changes to large strings because the large string gets copied. The pythonic way of dealing with this is to hold strings in an list and join them together once you have all the pieces.

Tags:

Python

String