Site icon DesignLinux

Learn Python Identity Operator and Difference Between “==” and “IS” Operator

This article is mainly curated to explain an important operator in python (“IDENTITY OPERATOR”) and how an identity operator differs (is, is not) from comparison operator (==).

IDENTITY OPERATOR

Identity operator (“is” and “is not”) is used to compare the object’s memory location. When an object is created in memory a unique memory address is allocated to that object.

  • ‘==’ compares if both the object values are identical or not.
  • ‘is’ compares if both the object belongs to the same memory location.

Create three string objects Name, Name1, and Name2. String object Name and Name2 will hold the same value and Name1 will hold different values.

When we create these objects, what happens behind the scene is, that object will be created in memory and will be available during the lifetime of the program.

Now you can use a comparison operator “==” to check if both the object values are the same. The output of the comparison operator will be a Boolean (True or False) value.

Create and Compare Objects

Create and Compare Objects

Now that you have compared two values to determine for equality, let us take a look at how the identity operator works.

The built-in Id() a function is used to get the “identity” of an object. An integer that will be unique and constant for the object during its lifetime.

To make it simple think this as unique government ID or Emp ID assigned to you, likewise a unique integer value is assigned for each object.

Unique Integer Value

Now you can compare 2 object references using “is” operator.

Identity Operator

When I compare Name and Name1 or Name2 using the identity operator what it does at the backend is it simply runs “id(Name) == id(Name2)”. Since id(Name) and id(Name2) both share the same memory location, it returns True.

Now here comes the interesting part. Look at our previous example where both Name and Name1 have identical values and returns the same integer value when we run id() function. Why do you think “Name_new” and “Name_le” object is not identical even though they share the same values from the below screenshot?

Integer Values

This is because of the python design implementation. When you create an integer object in range (-5,256) and string objects greater than or equal to 20 chars, instead of creating different objects at memory for the same value these objects act as a pointer to already created objects.

Below pictorial representation will give you a clear idea of what we have seen so far in this article.

Diagrammatic Representation

Summary

In this article, we have seen what is an identity operator. How comparison operator and identity operator is used, design implementation on how an object is created in memory.

Sharing is Caring…
Share on FacebookShare on TwitterShare on LinkedinShare on Reddit
Exit mobile version