Sunday, February 6, 2011

Python - how to pass by reference

While reading this blog post, I came upon the following trick to pass a list into function and have it be mutated i.e. by-reference semantics

Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = [10, 20]
>>> print x
[10, 20]
>>> def foo(x): x = [30];
...
>>> foo(x)
>>> x
[10, 20] # the assignment of [30] to x inside foo failed

>>> def bar(x): x[:] = [30]
...
>>> bar(x)
>>> x
[30]
>>>