By value or by reference?

Oliver Fromme olli at haluter.fromme.com
Mon Oct 18 18:13:39 CEST 2004


Jonathan  Ellis wrote:
 > Roger Irwin wrote:
 > > Riccardo Rossi wrote:
 > > > How does Python pass arguments to a function? By value or by reference?
 > > 
 > > By reference to an object....See the python tutorial.
 > 
 > Wrong.  Here is the difference between pass by reference and pass by
 > value to CS types:
 > 
 > > > > def foo(a): a = 1
 > ...
 > > > > i = 10
 > > > > foo(i)
 > > > > print i
 > 
 > With pass-by-reference, i would now be 1.  However, since python is
 > pass-by-value, it remains 10.

It remains 10 because integers are immutable, so the function
code cannot modify the caller's variable anyway.  However, if
you pass a mutable variable, things look a little different:

>>> def foo(a): a[0] = 1
...
>>> i = [10]
>>> foo(i)
>>> print i
[1]

Best regards
   Oliver

-- 
Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany

``All that we see or seem is just a dream within a dream.''
(E. A. Poe)



More information about the Python-list mailing list