Wednesday, March 25, 2015

Python: pass by value or reference?

If you Google for "python pass by value" (or reference), you'll find a lot of tortured discussion about whether python passes by object reference or not. Some will even prevaricate and say "neither". I finally realised what python was doing just by looking at a question on stackexchange:

Someone had asked why "somelist = someotherlist" was causing both lists to be modified. Someone posted that when you assign "a = b", you've just updated the object reference and they are the same object now. Then it dawned on me how python works, so I came up with the following example:

In C, a variable is a pointer to memory. So when you say:

a = 5;
a = 6;

When you are done, a (memory pointing to value) is 6. There is no "5" because that value was overwritten. In python when you do the above, you get two values and one reference. The variable a references object "6" and object "5" is orphaned.

 I diagrammed the following:

You can see that python doesn't change the value, just the reference. And this is why assignments in python are not always doing what you naively believe. That is why passing a list around in python is easy and works without return values or worrying about scope.

What if you want to pass by value? You have to use an immutable object (like a string or a tuple). If you want to use numbers, you probably have to make a copy.

Weekly writing output

Wordcount graph
Powered by WritersDB.com