0
0
Pythonprogramming~5 mins

Identity operators (is, is not) in Python

Choose your learning style9 modes available
Introduction

Identity operators check if two things are actually the same object in memory, not just if they look the same.

When you want to know if two variables point to the exact same thing.
When comparing objects where being the same object matters, like singletons.
When checking if a variable is None using 'is' for clarity and correctness.
Syntax
Python
variable1 is variable2
variable1 is not variable2

is returns True if both variables point to the same object.

is not returns True if they point to different objects.

Examples
Both variables point to the same list, so is returns True.
Python
a = [1, 2, 3]
b = a
print(a is b)  # True
Both lists look the same but are different objects, so is returns False.
Python
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b)  # False
Use is to check if a variable is None.
Python
x = None
print(x is None)  # True
Since x and y are different objects, is not returns True.
Python
x = 5
y = 10
print(x is not y)  # True
Sample Program

This program shows how is and is not work by comparing lists and checking for None.

Python
a = [1, 2, 3]
b = a
c = [1, 2, 3]

print('a is b:', a is b)
print('a is c:', a is c)
print('a is not c:', a is not c)

x = None
print('x is None:', x is None)
OutputSuccess
Important Notes

Use is only to check if two variables are the same object, not to compare values.

For value comparison, use == instead.

Checking for None should always use is None or is not None for clarity.

Summary

is checks if two variables point to the same object.

is not checks if they point to different objects.

Use these operators when object identity matters, like checking for None.