faqts : Computers : Programming : Languages : Python : Language and Syntax

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

71 of 88 people (81%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How does Python do parameter passing, by value or by reference?

Jul 17th, 2002 08:02
Michael Chermside, Ian Bicking, Rob van Wees,


Python does everything by reference, including parameter passing.
However, since variables are just bindings, not storage locations, 
setting a (local) variable inside a function will have no effect 
outside of the function (unlike reference passing in Pascal or C).
Here's an illustration:
Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 3
>>> def changeIt(y):
...     y = 5
...
>>> changeIt(x)
>>> x
3
Notice how it DIDN'T change, since changing "y" (local) to refer to the
integer 5 didn't affect the fact that "x" (global) still referred to the
integer 3.
However, the following looks a little different:
>>> x = [1,2,3]
>>> def changeIt(y):
...     y.extend( [4,5,6] )
...
>>> changeIt(x)
>>> x
[1, 2, 3, 4, 5, 6]
This time, we changed the OBJECT that both "y" (local) and "x" (global)
referred to. So the changes are seen in both variables.