Python id() Function

Returns a unique id of an object

Usage

The id() function returns a unique id for the specified object.

Syntax

id(object)

Python id() function parameters
ParameterConditionDescription
objectRequiredAny object (such as number, string, list, class etc.)

What is ID of an Object?

In Python, every object has its own unique id. Every time you create an object, a unique id is assigned to it.

The id is nothing but the address of the object in memory. So, it will be different for each time you run the program. But, there are some exceptions.

Basic Examples

Use id() function to get a unique id of the object.

x = id('Hello!')
print(x)
# Prints 34936992

x = id(9999)
print(x)
# Prints 33739544

L = ['red', 'green', 'blue']
x = id(L)
print(x)
# Prints 33866256

class myfunc:
  pass
o = myfunc()
print(id(o))
# Prints 33666912

Compare Two IDs

To check if two objects have same id, use is keyword.

# Check if 'x' and 'y' have the same id (point to the same object)
x = 42
y = x
print(x is y)
# Prints True

is keyword is used for identity (id) comparison, while == operator is used for equality (value) comparison.

Some Exceptions

In Python, every object has its own unique id. However, for the sake of optimization there are some exceptions.

Some objects have same id (actually one object with multiple pointer), like

  • Small integers between -5 and 256
  • Small interned strings (usually less than 20 character)
print(30 is 20+10)
# Prints True

print('aa'*2 is 'a'*4)
# Prints True