Python Basic Doubt

K

Krishnan Shankar

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

I am actually assigning new value to c. But from the value of id() all
three variables take same location. With variables a and b it is ok. But
why c taking the same location?

Regards,
Krishnan
 
R

Roy Smith

Krishnan Shankar said:
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.

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top