Variables with cross-module usage

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Nov 29 01:02:41 EST 2009


On Sat, 28 Nov 2009 22:18:11 -0500, Nitin Changlani wrote:

> Thanks for the reply MRAB, Rami, Matt and Mel,
> 
> I was assuming that since one.myList0] = one.a, the change in one.a will
> ultimately trickle down to myList[0] whenever myList[0] is printed or
> used in an expression. It doesn't come intuitively to me as to why that
> should not happen. Can you kindly suggest what is the correct way to go
> about it?


You are confusing *names* and *objects*. The presence or absence of a 
module qualifier is irrelevant, so for simplicity I will avoid it. I will 
use ` ` quotation marks to refer to names, to avoid confusing them with 
strings.


The Python statement 

a = "some text"

creates a name `a` which is bound to the object "some text".

myList[0] = a

stores the object bound to the name `a` to the first position of myList, 
not the name itself. So myList[0] ends up being "some text", but it has 
no idea whether it came from the name `a` or somewhere else.

Then when you execute:

a = "different text"

the name `a` is bound to the object "different text". But this doesn't 
affect myList[0] at all, because you're not changing the object "some 
text" -- strings are immutable and can't be changed.



-- 
Steven



More information about the Python-list mailing list