Python Identity Operators
Identity Operators in Python
Identity operators are used to compare the memory locations of two objects. They check whether two variables refer to the same object in memory, rather than comparing their values. Python provides two identity operators: is
and is not
.
List of Identity Operators
Operator | Description | Example |
---|---|---|
is | Returns True if both operands refer to the same object | a is b |
is not | Returns True if both operands do not refer to the same object | a is not b |
Examples of Identity Operators
1. Using the is
Operator
The is
operator checks if two variables point to the same object in memory.
2. Using the is not
Operator
The is not
operator checks if two variables do not point to the same object.
More Examples with Different Data Types
1. Using Identity Operators with Numbers
2. Using Identity Operators with Strings
Note on Interning
Python may optimize memory usage by reusing immutable objects (like small integers and short strings) for performance reasons. This is called interning. For instance, small integers between -5 and 256 are interned by default.
Summary of Identity Operators:
is
: ReturnsTrue
if both operands refer to the same object in memory.is not
: ReturnsTrue
if both operands do not refer to the same object in memory.
Identity operators are useful when you want to check if two references point to the same object, especially in cases where objects are mutable or when dealing with performance-sensitive applications.