Is Python Pass-By-Value Or Pass-By-Reference?

21 Mar 2015

The short answer is NEITHER. The complete answer is:

Everything in Python is an object, and object references are passed by value. Some people call it pass by object reference.

What matters is what you can do with the object references passed to a function. There are two cases here: mutable object and immutable object.

For mutable objects like lists, you can use the object reference to read the original object, to modify the contents of the original object, or to rebind the object reference to another object created inside the function; after rebound to another object, whatever you do with the object reference will not affect the original object, since the reference is now refering to the new object created inside the function.

For immutable objects like strings, you can almost do the same: use the object reference to read the original object and rebind the reference to another object, but NOT modifying the original object; this is not possible because it is immutable!

Variables in Python are just names or tags to objects, they are not the same as objects themselves. Check out python memory management to find out what that means! You might find it a smart way to manage memory!

Additionally, you can also figure out how python treats variables and objects by using python id (identity) function to get object address information, for example:

In [1]: a = 1

In [2]: hex(id(a))
Out[2]: '0x257e158'

In [3]: b = 1

In [4]: hex(id(b))
Out[4]: '0x257e158'

In [8]: a = 2

In [9]: hex(id(a))
Out[9]: '0x257e140'

FURTHER READINGS