Reference or Value?

MRAB google at mrabarnett.plus.com
Sun Feb 22 11:09:26 EST 2009


Torsten Mohr wrote:
> Hi,
> 
> how is the rule in Python, if i pass objects to a function, when is this
> done by reference and when is it by value?
> 
> def f1(a):
>     a = 7
> 
> b = 3
> f1(b)
> print b
> => 3
> 
> Integers are obviously passed by value, lists and dicts by reference.
> 
> Is there a general rule?  Some common formulation?
> 
They are all passed the same way:

def f2(a):
     a = [7]

b = [3]
f2(b)
print b
=> [3]

It's just that lists and dicts are containers whose contents you can
change (they are mutable), but integers aren't containers (they are
immutable).

Tuples are also containers, but you can't change their contents (they
are immutable).



More information about the Python-list mailing list