Variable Scope 2 -- Thanks for 1.

Irmen de Jong irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Fri Jan 9 16:01:42 EST 2004


Jens Thiede wrote:

> I found the querk in my code:
> 
> a = [1, 2, 3];
> b = a;
> b.append(4);

First: please remove the   ;    from the end of your lines...


> b == [1, 2, 3, 4]; # As it should.
> a == [1, 2, 3, 4]; # - Why?
> 
> One would think that b is a referance to a - however I know it's not.

It's not. a and b are both a name (or a reference to) the same
list object [1,2,3].  (notice the subtle difference !)


> Without changing a thing from above, the following is true:
> 
> b = [];
> b.append(5);
> a == [1, 2, 3, 4];
> b == [5];
> 
> How do I avoid accedentaly modifying variables, is this a bug? If not
> why not?

It's not a bug. It's the way Python works :-)

A very important concept with Python is that you don't have variable 
assignment, but name binding. An "assignment statement" binds a name on an 
object, and the object can be of any type. A statement like this:

age = 29

doesn't assign the value 29 to the variable age. Rather, it labels the integer 
object 29 with the name age. The exact same object can be given many names, 
that is, many different "variables" can refer to the same value object:

firstName = login = recordName = "phil"

All three names now refer to the same string object "phil". Because assignment 
in Python works this way, there are also no (type)declarations. You can 
introduce a new name when you want, where you want, and attach it to any 
object (of any type), and attach it to another object (of any type) when you 
feel like it. For instance, if the line above has been executed and we then do

login=20030405

the name login now refers to an int object 20030405, while firstName and 
recordName still refer to the old string "phil".

That's why b in your second example, is changed. b becomes a name for
a different list object (namely, the empty list []). a still refers to
the original list.

HTH,
--Irmen.



More information about the Python-list mailing list