Alex Rivera | Logout

Python: How do I pass a string by reference?

Asked 2012-11-28T15:45:25.530
45

From this link: How do I pass a variable by reference?, we know, Python will copy a string (an immutable type variable) when it is passed to a function as a parameter, but I think it will waste memory if the string is huge. In many cases, we need to use functions to wrap some operations for strings, so I want to know how to do it more effective?

Edit
Report

1 Answer

53

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.

answered 2012-11-28T15:46:49.930

Your Answer