Reference or Value?

afriere at yahoo.co.uk afriere at yahoo.co.uk
Mon Feb 23 02:52:10 EST 2009


On Feb 23, 2:13 am, Torsten Mohr <tm... at s.netic.de> 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?
>
> Thanks for any hints,
> Torsten.

Let's add some comments and a little code

>>>def f1 (a) :
      print a, id(a)
      #print the object passed and it's id
      a = 7
      #reassign 'a' to point to a different object
      print a, id(a)
      #print the new object and it's id

>>> b = 1
>>> #make 'b' refer to object '1' residing at a particular memory location
>>> id(b)
161120104
>>> #which we might refer to as 161120104
>>> f1(b) #pass the object '1' refered to by 'b' to our function
1 161120104
7 161120032
>>> #no surprises there, the new object has a different id.
>>> id(b)
161120104
>>> #no surprises ther, b (unlike the name internal to the function
>>> #hasn't been reassigned, so it still points where it always has
>>> #which is of course ..
>>> b
1
>>> z = []
>>> #name 'z' refers to an empty list
>>> id(z)
162432780
>>> f1(z)
[] 162432780
7 161120032
>>> #no surprise that the empty list object has the same id outside
>>> #and inside the function
>>> #stranger is that the '7' object has the same id as the 7 object
>>> #created on the previous run on the function, but that is another
>>> #story



More information about the Python-list mailing list