Explanation of list reference

Ryan Gonzalez rymg19 at gmail.com
Fri Feb 14 19:31:56 CET 2014

On 02/14/2014 12:08 PM, dave em wrote:
> Hello,
> Background:  My twelve y/o son and I are still working our way through Invent Your Own Computer Games with Python, 2nd Edition.
> (We finished the Khan Academy Javascript Tutorials is the extent of our experience)
> He is asking a question I am having trouble answering which is how a variable containing a value differs from a variable containing a list or more specifically a list reference.
> I tried the to explain as best I can remember is that a variable is assigned to a specific memory location with a value inside of it.  Therefore, the variable is kind of self contained and if you change the variable, you change the value in that specific memory location.
> However, when a variable contains a list reference, the memory location of the variable points to a separate memory location that stores the list.  It is also possible to have multiple variable that point to the memory location of the list reference.  And all of those variable can act upon the list reference.
> Question:  Is my explanation correct?  If not please set me straight :)
> And does anyone have an easier to digest explanation?
> Thanks in advance,
> Dave

You've got it backwards. In Python, /everything/ is a reference. The 
variable is just a "pointer" to the actual value. When you change a 
variable, you're just changing the memory location it points to.

Strings, ints, tuples, and floats behave differently because they're 
/immutable/. That means that they CANNOT modify themselves. That's why 
all of the string methods return a new string. It also means that, when 
you pass one two a function, a /copy/ of it is made and passed instead.

So, back to the original subject. Everything is a reference. When you do 

|x = [1,2,3]
x = [4,5,6]

x now points to a different memory location. And, when you do this:

|x[0] =99000
x[0] =100

you're just changing the memory location that |x[0]| points to.

If anybody ever asks me why I prefer C++ to C, my answer will be simple: "It's becauseslejfp23(@#Q*(E*EIdc-SEGFAULT. Wait, I don't think that was nul-terminated."

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140214/5c6affbe/attachment.html>

More information about the Python-list mailing list