Reputation: 59
I am relatively new to python and would like to settle a dispute I am having with someone. Suppose you were given an exam or quiz and the following question appeared:
Question 32: In the following python [IDLE] example:
>>> x=52
>>> x
52
>>> id(x)
505404728
505404728 is:
Please provide an explanation. Thanks everyone!
Upvotes: 3
Views: 356
Reputation: 22953
I'd say the correct answer is c
. id(x)
returns the ID of the object that x
refers to, 52
. So c
is correct. Here's why I didn't choose the others:
c
is 52
, not 505409528
. Also, x
doesn't "hold" anything. It is a label that refers to the object 52
.x
its self does not have an ID. It's simply a label. 52
- the object it's label-ing or referring to - does have an ID.In the future, to be able to fully understand and answer questions such as the one you posted, you need to have a firm understand of what variables are in Python. The defacto resource is an article by Ned Batchelder titled Facts and myths about Python names and values.
Upvotes: 2
Reputation: 3662
id
returns an integer that is guaranteed to be unique and constant for this object during its lifetime
>>> x = 52
>>> y = 52
>>> id(x)
12694616
>>> id(y)
12694616
Different python implementations (Cpython, Jython, etc) implement this differently - cpython for example returns the memory address of the object.
Update: Actually, Christian Dean's answer in the comments is more accurate: the answer is uhhhh .... 'c' ? Does the label x
have an id, or does is it a pointer to the value 52
?
Upvotes: 4
Reputation: 402333
A useful-to-know excerpt from the docs:
The current implementation keeps an array of integer objects for all integers between
-5
and256
, when you create anint
in that range you actually just get back a reference to the existing object.
So, to recap:
In [200]: x = 52
In [201]: id(x)
Out[201]: 4297372320
In [202]: id(52)
Out[202]: 4297372320
x
points to 52
. 52
is stored in memory somewhere. id
returns a "number" that is guaranteed to be unique for an object during its lifetime.
In short, the answer is d
, because x
and 52
have the same reference. You can argue that it might be c
though... depending on how you interpret the question.
Upvotes: 4