Python id() With Examples

Python id() function returns the “identity” of the object. The identity of an object is an integer, which 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. In CPython implementation, this is the address of the object in memory.

Python id()

Python cache the id() value of commonly used data types, such as string, integer, tuples etc. So you might find that multiple variables refer to the same object and have same id() value if their values are same.

Let’s check this out with an example.


Notice that id() value of ‘a’ and ‘b’ are same, they have the same integer value.

Let’s see if we get the similar behavior with string and tuples too?


From the output, it’s clear that Python cache the strings and tuple objects and use them to save memory space.

Caching can work only with immutable objects, notice that integer, string, tuples are immutable. So Python implementation can use caching to save memory space and improve performance.

We know that dictionary is not immutable, let’s see if id() is different for different dictionaries even if the elements are same?


As we thought, dict objects are returning different id() value and there seems no caching here.

Let’s see a simple example of getting id() value for a custom object.



Python id() value is guaranteed to be unique and constant for an object. We can use this to make sure two objects are referring to the same object in memory or not.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: