Reference or Value?

Duncan Booth duncan.booth at invalid.invalid
Sun Feb 22 10:47:16 EST 2009


Torsten Mohr <tmohr at s.netic.de> wrote:

> 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?

Yes, integers are 'obviously' passed by value, except that if they were you 
couldn't do this:

>>> x = 26*1000
>>> y = 26000
>>> id(x)==id(y)
False
>>> def whichint(arg):
	if id(arg)==id(x):
		print "You passed x"
	elif id(arg)==id(y):
		print "You passed y"

		
>>> whichint(x)
You passed x
>>> whichint(y)
You passed y


The general rule is that everything is passed in exactly the same way.



More information about the Python-list mailing list