What is the id() function in Python?

Overview

In Python, the id() function is used to return an object’s identity.

Syntax

id(object)

Parameter

  • object: This represents the identity to be returned.

Return value

This function returns an object’s identity.

Example

# create a class with a property
class Person:
name = "Maria"
# create object of the class
person = Person()
# get the id
print('Id:',id(person))
# create a variable
x = 10
print('Id:',id(x))
# create a list
my_list = [12, 3.5, "shot"]
print('Id:',id(my_list))

Explanation

  • Lines 2 and 3: We create a class named Person with a property named name.
  • Line 6: We create an object of the class named person.
  • Line 8: We display the identity of person using id().
  • Lines 11 and 12: We create a variable x and display its identity.
  • Lines 15 and 16: We create a list my_list and display its identity.

Free Resources