[Tutor] Still confused about Python references/objects

Rick Pasotto rick@niof.net
Sat, 31 Mar 2001 13:27:32 -0500


On Sat, Mar 31, 2001 at 09:54:04AM -0800, Sheila King wrote:
> However, just for illustration, I was trying to write a swap function. And, I
> thought that all parameters were passed by reference. So, when I ran the
> following interpreter session, I was really surprised to find that my swap
> function actually swapped nothing at all:
> 
> Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> IDLE 0.6 -- press F1 for help
> >>> x = 2
> >>> y = 3
> >>> print x, " ", y
> 2   3
> >>> (y, x) = (x, y)
> >>> print x, " ", y
> 3   2
> >>> def swap(a, b):
> 	(b, a) = (a, b)
> 
> >>> swap(x, y)
> >>> print x, " ", y
> 3   2
> >>> 
> 
> Could someone explain this to me? Why doesn't the swap function do anything?

How about this:

x and y are *names* given to the objects 3 and 2.

Within your swap function these objects (3 and 2) have the additional
names first of a and b and then of b and a.

Outside your function the names of the objects have not changed.

x and y are *not* the names of storage locations that can contain
different values. They are the names of the values themselves.

In python, when you write x = 2 you are saying that you want to refer to
the value of 2 by the name x. When you then say x = x + 1 you are saying
that from now on x is the name you will call the value 3 and unless the
value 2 is also known by another name it (ie, the value 2) disappears.

[Actually I think that, for performance reasons, small integers never
*really* disappear, but conceptually they do.]

-- 
"Disobedience is the true foundation of liberty.
The obedient must be slaves."
		-- Henry David Thoreau
		   Rick Pasotto email: rickp@telocity.com