Python Basic Doubt

Roy Smith roy at panix.com
Sat Aug 10 12:35:30 EDT 2013


In article <mailman.428.1376151419.1251.python-list at python.org>,
 Krishnan Shankar <i.am.songoku at gmail.com> wrote:

> Hi Fellow Python Friends,
> 
> I am new to Python and recently subscribed to the mailing list.I have a
> doubt regarding the basics of Python. Please help me in understanding the
> below concept.
> 
> So doubt is on variables and their contained value.
> 
> Why does in the below example from Interpreter exploration value of c take
> pre existing memory location.
> 
> >>> a=10
> >>> id(a)
> 21665504
> >>> b=a
> >>> id(b)
> 21665504
> >>> c=10
> >>> id(c)
> 21665504

Python doesn't really expose anything about memory locations.  The fact 
that id() returns something which looks like it might be a memory 
location is purely a detail of the particular implementation you're 
using.

The next thing to understand is that python doesn't have variables.  It 
has objects and names which are bound to those objects.  So, what's 
happening in your example is:

1) a = 10

You're creating an integer object with the value 10, and binding the 
name "a" to that object.

2) b = a

You're binding another name, "b" to the same object that "a" is bound to.

3) c = 10

This is the tricky one.  You're using 10 again as a literal, and the 
interpreter is reusing the same existing (interned) integer object, and 
binding yet another name, "c" to it.  This part is implementation 
dependent.  Nothing says Python must intern integer literals, it's 
entirely free to create a new integer object every time you utter 10 in 
your source code.



More information about the Python-list mailing list