Get an object's unique ID in Python

avatar

Borislav Hadzhiev

Last updated: Sep 8, 2022

banner

Photo from Unsplash

Get an object's unique ID in Python #

Use the id() function to get an object's unique ID, e.g. result = id(object). The id() function returns a unique integer that represents the identity of the provided object.

main.py
dict1 = {'name': 'bobbyhadz', 'salary': 100} print(id(dict1)) # 👉️ 140176720308032 dict2 = {'name': 'bobbyhadz', 'salary': 100} print(id(dict2)) # 👉️ 140176720308288 print(id(dict1) == id(dict2)) # 👉️ False

We used the id() function to get the identity of an object.

The function returns an integer, which is guaranteed to be unique and constant for the object's lifetime.

The id() function returns the address of the object in memory in CPython.

The following dictionaries are stored in different locations in memory, even though they store the same key-value pairs.

main.py
dict1 = {'name': 'bobbyhadz', 'salary': 100} print(id(dict1)) # 👉️ 140176720308032 dict2 = {'name': 'bobbyhadz', 'salary': 100} print(id(dict2)) # 👉️ 140176720308288 print(id(dict1) == id(dict2)) # 👉️ False

If two variables refer to the same object, they will point to the same location in memory and will have the same ID.

main.py
dict1 = {'name': 'bobbyhadz', 'salary': 100} print(id(dict1)) # 👉️ 139807401338688 dict2 = dict1 print(id(dict2)) # 👉️ 139807401338688 print(id(dict1) == id(dict2)) # 👉️ True

This works a little differently when working with primitives (e.g. strings).

main.py
str1 = 'bobbyhadz.com' str2 = 'bobbyhadz.com' print(id(str1)) # 👉️ 139797744953264 print(id(str2)) # 👉️ 139797744953264 print(id(str1) == id(str1)) # 👉️ True

The two variables store the same string and point to the same location in memory, therefore they have the same ID.

Primitive, immutable objects like strings, integers and floats will always point to the same location in memory and have the same ID in the program.

Whereas non-primitive, mutable objects like lists and dictionaries might store the same values but point to different locations in memory and have multiple IDs.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.