Tuesday, December 07, 2010

Understanding pass by value and pass by reference - Python style

Continuing with the Python theme -

If you're a developer, please click here to see how you can make money helping others.

One of the guys on our Python discussion list wanted to know the difference between pass-by-value and pass-by-reference. Seeing how this same question has been asked a few time previously, I thought I would try and make a blog entry to give a simple explanation to demonstrate how it works.

Some languages use pass-by-value, but Python on the other hand uses pass-by-reference. What is the difference you ask?

Well pass by value is exactly what it sounds like - you pass the value (a copy of everything in the memory). This is bad when you're passing a 10,000 item list to a function - because you now have *two* 10,000 item lists. It's even worse when you have many times that amount of data.

Python, OTOH passes by reference - instead of copying the list, a pointer to the list is passed, so when you see something like this:

def do_something(a_list):
a_list[2] = 4

mylist = [1,2,3,4]
do_something(mylist)

now mylist is: [1,2,4,4].

In call-by-value, the value of the arguments are copied into the function. There is no way to modify variables outside of the function since you don't have access to them, only to copies. C uses this, among many others:

int a = 5
void func(int b) { b = 6; }
func(a);

a == 5; /* evaluates to true, variable outside function scope remains unchanged */

The value b, inside the function, contains a copy of a. So when it is
modified, the original a remains unchanged.

Many people call python pass-by-reference, even though this is technically incorrect. The difference comes from the semantics of variables and values. In languages such as C, a variable is an area of memory that contains something. An assignment then, copies the value on the right into the variable (memory) on the left.

There are lots of materials and books that cover object-oriented programming in Python comprehensively. But the one that I have personally used and always recommend is this nicely written title:

http://www.jroller.com/bookreview/entry/python_3_object_oriented_programming

Have your own thoughts on how to explain the difference between the two? We would like to hear them in the comment below.

No comments:

Related Posts with Thumbnails