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

OperatorDescriptionExample
isReturns True if both operands refer to the same objecta is b
is notReturns True if both operands do not refer to the same objecta 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.

a = [1, 2, 3] b = a # b refers to the same list object as a c = [1, 2, 3] # c refers to a different list object with the same values # Check if a and b are the same object print(a is b) # Output: True (both refer to the same object) # Check if a and c are the same object print(a is c) # Output: False (a and c are different objects)

2. Using the is not Operator

The is not operator checks if two variables do not point to the same object.

a = [1, 2, 3] b = a # b refers to the same list object as a c = [1, 2, 3] # c refers to a different list object # Check if a and b are the same object print(a is not b) # Output: False (a and b are the same object) # Check if a and c are not the same object print(a is not c) # Output: True (a and c are different objects)

More Examples with Different Data Types

1. Using Identity Operators with Numbers

x = 10 y = 10 z = 20 # Check identity for integers print(x is y) # Output: True (both point to the same integer object) # Check identity for different integers print(x is z) # Output: False (x and z are different objects)

2. Using Identity Operators with Strings

str1 = "hello" str2 = "hello" str3 = "world" # Check identity for strings print(str1 is str2) # Output: True (both point to the same string object in memory) # Check identity for different strings print(str1 is str3) # Output: False (str1 and str3 are different objects)

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.

a = 256 b = 256 print(a is b) # Output: True (both point to the same interned object) a = 257 b = 257 print(a is b) # Output: False (257 is not interned, so different objects)

Summary of Identity Operators:

  • is: Returns True if both operands refer to the same object in memory.
  • is not: Returns True 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.