Pass by reference?
Remco Gerlich
scarblac-spamtrap at pino.selwerd.nl
Thu May 25 05:25:45 EDT 2000
Dale Strickland-Clark wrote in comp.lang.python:
> Also the following program proves to me that arguments are passed by value
> and not by reference:
>
> def wibble(var):
> var = 1
>
> x = 0
> wibble(x)
> print x
>
> It prints 0 showing that the assignment in wibble is made to a copy of x
A key thing about Python. All arguments are passed by reference. But
*assignment* is by reference too!
x refers to the integer 0.
wibble is called, now the local var 'var' also refers to the integer 0.
after 'var = 1', 'var' refers to the integer 1. x is unchanged.
Variables are just names for objects. Assignment gives that name to another
object. Assignment can only *change* an object if you assign to something
'inside' the object, like 'x[3] = 4' or 'ob.value = 3'. Integers are
immutable, can't be changed. Just like strings and tuples. Lists can be
changed.
Compare:
x = []
def app(list, value):
list = list+[value]
return list
app(x, 3)
print x
With:
x = []
def app(list, value):
list.append(value)
return list
app(x, 3)
print x
--
Remco Gerlich, scarblac at pino.selwerd.nl
This is no way to be
Man ought to be free -- Ted Bundy
That man should be me
More information about the Python-list
mailing list