Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

identifying objects, why does the returned value from id(...) change?

Tags:

python

id(object)

This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.

Can you explain this output? Why does j's id change?

>>> i=10  
>>> id(i)  
6337824  
>>> j=10  
>>> id(j)  
6337824  
>>> j=j+1  
>>> id(j)  
6337800  
>>> id(i)  
6337824  
like image 550
anon Avatar asked Aug 04 '10 04:08

anon


People also ask

Do objects with the same ID have the same value?

"id is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value." tells us nothing much unless we both understand what sort of Python object t+t or obj.

Can Python object ID change?

It's a unique identifier for the object a refers to. It won't change for the lifetime of the object.

What will be the return value of id () function?

The id() function returns a unique id for the specified object. All objects in Python has its own unique id. The id is assigned to the object when it is created.

What is ID for an object?

id() is an inbuilt function in Python. Syntax: id(object) As we can see the function accepts a single parameter and is used to return the identity of an object. This identity has to be unique and constant for this object during the lifetime. Two objects with non-overlapping lifetimes may have the same id() value.


2 Answers

Because integers are immutable, each integer value is a distinct object with a unique id. The integer 10 has a different id from 11. Doing j=j+1 doesn't change the value of an existing integer object, rather it changes j to point to the object for 11.

Check out what happens when we independently create a new variable k and assign it the value 11:

>>> j=10
>>> id(j)
8402204
>>> j=j+1
>>> id(j)
8402192
>>> k=11
>>> id(k)
8402192

Note that it is not always the case that every integer has one and only one corresponding object. This only happens for small integers that Python decides to cache. It does not happen for large integers:

>>> x = 123456789
>>> id(x)
8404568
>>> y = 123456789
>>> id(y)
8404604

See https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong:

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.

like image 58
4 revs Avatar answered Sep 21 '22 12:09

4 revs


This is why 2**8 is 2**8 == True, and 2**9 is 2**9 == False.

Values between -5 and 256 are preallocated.

like image 30
Ning Sun Avatar answered Sep 20 '22 12:09

Ning Sun