Id() Function In Python

Function Name:



Function Signature:



Function Overview:

Every object has the following important properties.

  • State
  • Behavior
  • Identity


  • While the state represents the collective state of an object based on its attributes the behavior is driven by the methods it exposes.


  • Identity of an object involves the very existence of the object and means to access it.


  • In broad sense any valid reference to an object is an identity to an object. 


  • In C and C++ the id of an object means the pointer using which the object can be addressed. In C and C++, without the identity that is without the address of an object, the object cannot be accessed.


  • An object without a pointer to it does not exist in C and C++.


  • The same principles can be applied to Python as well. Identity means a valid identifier pointing to a living object.


  • Having discussed identity in length, the id() function however only gives a unique id of an object. In CPython implementation it is the address of an object.




class sample:

    def __init__(self, xval):

        self.x = xval      


# Create two identical strings

s1 = "Hello World"

s2 = "Hello World"


id1 = id(s1)

id2 = id(s2)





# Create two user defined objects with attribute x initialised to value 10

sample1 = sample(10)

sample2 = sample(10)


id3 = id(sample1)

id4 = id(sample2)











In the output above we could see that Python has optimized the implementation of string literals with the same value by having only one copy of it.

However when it comes to objects of user defined classes like the Sample class in the example, the id() function makes it clear that different objects

have different identities.

Copyright 2018 ©