[Tutor] Still confused about Python references/objects

Sheila King sheila@thinkspot.net
Sat, 31 Mar 2001 09:54:04 -0800


Even now, there is a discussion going on in comp.lang.python on this same
topic. Anyhow, I've been working with Python for a couple of months now, and
reading some books and online docs, and have written a few successful scripts
that I use on my website or for email management. And I THOUGHT I had figured
out this Python reference stuff (with respect to objects and names that refer
to them). <sigh> But I managed to confuse myself again this morning.

I really like how it is not necessary to write a "swap" function in Python.
The whole "swap" procedure can be accomplished in Python with a single
assignment statement using tuples. I saw this type of example in Wesley Chun's
_Core Python Programming_ book.

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?

--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/