Chris C
Chris C

Reputation: 59

Python id() with variable reference to an object

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

Answers (3)

Chris
Chris

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:

  • a: Option a is blatantly incorrect. We don't even have to search for a definitive answer. We can clearly see that value of c is 52, not 505409528. Also, x doesn't "hold" anything. It is a label that refers to the object 52.
  • b: Option b although better, is still incorrect. The variable 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.
  • d: I didn't choose this one for the reason I didn't choose b.
  • e: The option is also incorrect. As I said above, I believe the correct answer is c.

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

Danielle M.
Danielle M.

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

cs95
cs95

Reputation: 402333

A useful-to-know excerpt from the docs:

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int 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

Related Questions