Variable Scope 2 -- Thanks for 1.

JCM joshway_without_spam at myway.com
Fri Jan 9 21:56:26 CET 2004


Jens Thiede <jensthiede at webgear.co.za> wrote:
> I found the querk in my code:

> a = [1, 2, 3];
> b = a;
> b.append(4);

> 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.

Rather, a and b hold references to the same object--the list created
by the expression [1, 2, 3].

> 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?

Assignment rebinds variables to different objects, so b now holds a
reference to the list created by the expression [].



More information about the Python-list mailing list