[Tutor] list method help

Kent Johnson kent37 at tds.net
Fri Feb 3 22:38:22 CET 2006


Rinzwind wrote:
> On 2/3/06, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> wrote:
>     You definitely have to stop thinking of variables as containers. They
>     are pointers or references to values. Another way to think of this is
>     that variables are names for things. You may call me Kent, someone else
>     might call me Mr. Johnson or Dad, but if I get a haircut, Kent, Mr.
>     Johnson and Dad all have shorter hair because all three names refer to
>     the same person.
> 
>     Python works the same way. Assignment binds a name to a value. So if
>     I say
>        lst = [0, 1, 2]
>     I have bound the name 'lst' to a particular list whose value, at the
>     moment, is [0, 1, 2]. If I then assign
>        a = lst
>     this binds the name 'a' to the same value (the list) that 'lst' is bound
>     to. If I change the bound list, you will see the change whether you
>     access the list through the name 'a' or the name 'lst'.
> 
> Kent that's a perfectly understandable and easy to grasp analogy. But it 
> stays just an analogy ;-)

The first paragraph above is analogy, the second is commonly used Python 
terminology. For example, from the Language Reference: "Assignment 
statements are used to (re)bind names to values."
http://docs.python.org/dev/ref/assignment.html

> Coding is alot easier bacause it does not require that 2 variables need 
> to be linked. I have been coding with the knowledge A is A and A is 
> never B. Not even if they contain the same content but they can have the 
> content copied from 1 to another :-P
> 
> My question might be summed up to:
> When would I have need of this?  Or why do I want it? Where is the benefit?

You are suggesting that assignment copy values, rather than references 
to values. This could be very expensive. For example if you want to pass 
a large list to a function, passing just a reference to the list is much 
easier than passing a copy of the list.

References are used in other languages, too. With the exception of 
primitive values (int, float, char, etc) Java variables have exactly the 
semantics of Python variables - they are references to objects, and 
assignment copies the reference, not the value. C and C++ can use 
pointers to structures which are similar to Java and Python references. 
So Python is not really so odd, it's just different than what you are 
used to and expect.

> But this assignment sort of puzzles me to why it's done like this (maybe 
> cuz I am not used to it and can not see beyond my own experience in 
> coding (having a blind spot or something like that)).
> 
> Oh and tell me to shut up and just accept it if you want to ;-)

Good idea. Just get over it, it's really not a big deal. ;-) It's only a 
problem if you try to hold on to the copying model, then you will be 
occasionally surprised.

Kent



More information about the Tutor mailing list