6️⃣ Identity Operators

  • Python has two identity operators (is, is not). It checks whether two objects are identical or not and returns result as a boolean value.

  • In python everything (variable, list, tuple, class, function, datatype, …) is object. Two objects are said to be identical if both memory locations (ids) are same.

  • Memory locations are the location names to which the objects are store into memory. We can find memory location of variable by applying id method on it.

Lets define two variables ‘a’,’b’ and ‘c’.

💻 Example:

1
2
3
a = 10
b = 10
c = 10.0

Lets find their memory locations using id method.

1
2
3
print(id(a))
print(id(b))
print(id(c))

✅ Output:

140724273022928
140724273022928
2951713442736

1) is:

It returns True if both the objects are identical i.e both having same memory locations, otherwise it returns False. As the memory locations of objects ‘a’ and ‘b’ are same, so they are identical.

💻 Example:

1
2
print(a is b)
print(a is c)

✅ Output:

True
False

💻 Example:

1
2
3
4
5
6
# Python program to illustrate the use of 'is' identity operator
x = 5
y = 5
print(x is y)
print(id(x))
print(id(y))

✅ Output:

True
2505534106032
2505534106032

2) is not:

It returns True if both the objects are not identical i.e both having different memory locations, otherwise it returns False. As the memory location of object ‘c’ is different with ‘a’ and ‘b’, so they are not identical.

💻 Example:

1
2
3
print(a is not c)
print(b is not c)
print(a is not b)

✅ Output:

True
True
False

💻 Example:

1
2
3
4
5
6
7
# Python program to illustrate the use of 'is not' identity operator

x = 5
if (type(x) is not int):
    print("true")
else:
    print("false")

✅ Output:

false

Follow below video to clear the concepts practically. Membership and identity operators are explained in detail.


Be prepared with below questions prior to your interview !

Frequently asked Interview Questions
  1. What are identity operators in Python?

  2. How does the ‘is’ operator work in Python?

  3. Explain the ‘is not’ operator in Python.

  4. What is the difference between (a is b) and (a == b)?