How does Python (v2.1.1) handle parameter passing? By value or by reference?

Rob van Wees r.vanwees at chello.nl
Wed Aug 22 17:57:43 EDT 2001


Hi all,

As a newbie to Python, I'm having trouble finding out how the interpreter
handles parameters that are passed to functions. Sometimes they seem to be
handled as values and sometimes as references.

The Python documentation does not seem to answer my question. Could any of
you help me?

Below is a copy of an IDLE session to find out what Python does with
parameters. It shows the different behaviors of the interpreter. I defined 3
functions that print and then change the parameters to see the effects on x
and y. The results seem weird to me. Anyone knows what is happening here?

TIA,

Rob.

--------------------------------------- IDLE session
below ---------------------------------------

Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> def f1(x,y):
                print x, " - ", y
                x = x + 2
                y = y - 2

>>> def f2(x, y):
            print x, " - ", y
            x.append(2)
            y.append(-2)


>>> def f3(x,y):
            print x, " - ", y
            x = [1,2,3,4]
            y = [4,3,2,1]

>>> x = 1
>>> y = 2
>>> f1(x,y)
1  -  2
>>> print x, " - ", y
1  -  2
>>> x = [1]
>>> y = [2]
>>> f2(x,y)
[1]  -  [2]
>>> print x, " - ", y
[1, 2]  -  [2, -2]
>>> f3(x,y)
[1, 2]  -  [2, -2]
>>> print x, " - ", y
[1, 2]  -  [2, -2]
>>>





More information about the Python-list mailing list