Passing arguments to function - (The fundamentals are confusing me)

Christopher Subich spam.csubich+block at block.subich.spam.com
Tue Aug 9 11:19:45 EDT 2005


Gregory Piñero wrote:
> Hey guys, would someone mind giving me a quick rundown of how
> references work in Python when passing arguments into functions?  The
> code below should highlight my specific confusion:

All arguments are passed by reference, but in Python equality rebinds 
the name.

> 
> <code>
> 
> bool1=True
> lst1=[1,2,3]
> 
> def func1(arg1): arg1.append(4)

In C++, pretending it had dynamic typing, this would be equivalent to:
void func1( * arg1){
    arg1->append(4);
}

> 
> def func2(arg1): arg1=False
void func2 ( * arg2) {
    arg2 = &(False);

> Why does my list variable get changed for the rest of the program, but
> my boolean variable doesn't.  What am I not understanding?

In Python, "x = y" has a very definite meaning of "y is assigned to the 
name of x."  This change does not affect whatever was in x to start 
with, and it certainly would not affect anything else which holds a 
reference to the object formerly known as x.

In contrast, calling a function which mutates the object (like .append 
on lists, or assignment by lst[index]=something) actually changes the 
object itself, which is of course reflected by all other names that hold 
a reference to the object.



More information about the Python-list mailing list