Pass by reference ?

Quinn Dunkan quinn at groat.ugcs.caltech.edu
Mon Apr 3 06:02:06 EDT 2000


On Mon, 03 Apr 2000 10:30:49 +0100, Jacek Generowicz <jmg at ecs.soton.ac.uk>
wrote:
>Hi,
>
>I'm just trying to familiarize myself with Python.
>In Magnus Lie Hatland's Instant Python, he
>mentions that `all parameters in Python are passed
>by reference'.
>
>So I tried the following code:
>
>#!/usr/bin/python
>
>def increment(x):
>    x = x + 1
>    return x

This makes a *new* local x, which disappears when it goes out of scope.
Whenever you write "<var> = <blah>" python *always* makes a new local binding
of blah to var, unless you've got a "global <var>" up there somewhere.

You can't modify numbers in python anyway (they're immutable, just like
strings).  Try it with a mutable object like a list to see 'pass by reference'
behaviour:

>>> def addelt(lst, x):
...     lst.append(x)
...
>>> a = [0, 1]
>>> addelt(a, 5)
>>> a
[0, 1, 5]



More information about the Python-list mailing list