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.

Example:

# string
x = id('Hello!')
print(x)	# 34936992
# number
x = id(9999)
print(x)	# 33739544
# list
L = ['red', 'green', 'blue']
x = id(L)
print(x)	# 33866256
# custom object
class myfunc:
  pass

o = myfunc()
print(id(o))	# 33666912

Compare Two IDs

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

Example: Check if ‘x’ and ‘y’ have the same id (point to the same object)

x = 42
y = x
print(x is y)  # 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)

You can check this fact like following:

Example:

>>> 30 is 20+10
True
 
>>> 300 is 200+100
False

>>> 'aa'*2 is 'a'*4
True

>>> 'aa'*20 is 'a'*40
False