[Tutor] Confused about functions

alan.gauld@bt.com alan.gauld@bt.com
Thu, 1 Nov 2001 18:17:22 -0000


> X = 1
> L = [1, 2]
> changer (X, L)
> 
> at the end of the code, the value of X remains 1, 
> because x is only set to 2 on a local level within 
> the function. However, L has chaned to ['spam',2].

No. L has not changed at all. L is a reference to 
a list object. The list object itself is still 
the same list, what has changed is the contents 
of the list.

Now redefine changer() slightly:

>>> def changer(x,y):
...   x = 2
...   y = [3,4] #<-- try to assign a new list
...
>>> changer(X,L)
>>> X,L
(42, ['foo', 2])

Now what happens is function changer() tries to assign 
a new list to y which is representing L. But it can't 
change L so it creates a new local L referencing the 
new list. This then gets lost when the function returns 
and the global L retains its original list.

> Also, does anyone have an opinion on the Python Essential 
> Referance from New Riders? 

The best Python reference book around bar the online 
manuals - which you can also get in print...

> How does it compare to O'Reilly's Programming 
> Python 

Different kind of book. PP explains how/why Python works, 
Essential Python just tells you what it does and how to 
use it. I'd recommend both of these books.

> Standard Library book?

More like EP but not as good IMHO - more like a cookbook 
of handy tips and examples etc.

Alan G.