Pass by reference ?

Jacek Generowicz jmg at ecs.soton.ac.uk
Wed Apr 5 18:03:08 CEST 2000


Michael Hudson wrote:

> Python never ever copies anything when you pass it as an argument to a
> function - it's just that sometimes the things you pass are immutable
> - which is when it looks like call by value - and sometimes they're
> mutable - when it looks a bit like call by reference.

Not necessarily; consider the following (and please excuse my Python-naive
coding style):

def looks_like_by_value( a ):
    a = a + 1
    print a

def looks_like_by_reference( a ):
    a.append('x')
    print a

def looks_like_by_value_again( a ):
    a = a + ['x']
    print a

a = 3
print a
looks_like_by_value( a )
print a; print

a = [ 1,2,3 ]
print a
looks_like_by_reference( a )
print a; print

a = [ 1,2,3 ]
print a
looks_like_by_value_again( a )
print a; print
============
output:

3
4
3

[1, 2, 3]
[1, 2, 3, 'x']
[1, 2, 3, 'x']

[1, 2, 3]
[1, 2, 3, 'x']
[1, 2, 3]


So whether the call resembles by-reference or by-value depends on what you do
with the mutable object.

Jacek





More information about the Python-list mailing list