Pass by reference ?

Fredrik Lundh effbot at telia.com
Mon Apr 3 05:51:22 EDT 2000


Jacek Generowicz <jmg at ecs.soton.ac.uk> wrote:
> def increment(x):
>     x = x + 1
>     return x
>
> a = 0
> print a
> print increment(a)
> print a
> ====================
>
> output:
>
> 0
> 1
> 0
>
> Given my understanding of passing by reference,
> the last number should be 1.
>
> What am I missing ?

two things, at least:

-- python variables are names that points to a value.

-- python's assignment statement doesn't modify values,
   it modify names.  "x = y" means "change 'x' so it points
   to the current value of 'y'", not "copy the value of 'y'
   into 'x'"

so in this case, "x = x + 1" means

    "calculate the sum of 'x' plus one, and change 'x' to point
    to that sum",

instead of

    "replace the value pointed to by 'x' with the sum"

the only way to modify a value in place is to call a method on it
(directly, or through syntactic sugar like member assignment)

</F>





More information about the Python-list mailing list