Understanding python functions - Instant Python tutorial

Chris Carlen crcarleRemoveThis at BOGUSsandia.gov
Fri Jul 13 02:51:08 CEST 2007


I have begun learning Python by experimenting with the code snippets here:


In the section on functions, Magnus Lie Hetland writes:

For those of you who understand it: When you pass a parameter to a 
function, you bind the parameter to the value, thus creating a new 
reference. If you change the “contents” of this parameter name (i.e. 
rebind it) that won’t affect the original. This works just like in Java, 
for instance. Let’s take a look at an example:

def change(some_list):
     some_list[1] = 4

x = [1,2,3]
print x # Prints out [1,4,3]

As you can see, it is the original list that is passed in, and if the 
function changes it, these changes carry over to the place where the 
function was called.  Note, however the behaviour in the following example:

def nochange(x):
     x = 0

y = 1
print y # Prints out 1

Why is there no change now? Because we don’t change the value! The value 
that is passed in is the number 1 — we can’t change a number in the same 
way that we change a list. The number 1 is (and will always be) the 
number 1. What we did do is change the contents of the local variable 
(parameter) x, and this does not carry over to the environment.

What this looks like to me is what would happen if in C I passed a 
pointer to the list x to the function change(), as in:


Thus the function could change the original list.

I don't understand Hetland's terminology though, when he is speaking of 
"binding" and "reference."  Actually, Hetland's entire first paragraph 
is unclear.

Can anyone reword this in a way that is understandable?


Good day!

Christopher R. Carlen
Principal Laser&Electronics Technologist
Sandia National Laboratories CA USA
crcarleRemoveThis at BOGUSsandia.gov
NOTE, delete texts: "RemoveThis" and
"BOGUS" from email address to reply.

More information about the Python-list mailing list