Membership and identity operators are used to test specific conditions in Python programs. While membership operators check whether a value exists inside a sequence, identity operators check whether two variables refer to the same object in memory.
Understanding these operators helps in writing efficient and logical programs.
MEMBERSHIP OPERATORS
Membership operators are used to check whether a value is present in a sequence such as a string, list, or tuple.
There are two membership operators:
in
not in
IN OPERATOR
The in operator returns True if the specified value exists in the sequence.
Example:
numbers = [1, 2, 3, 4, 5]
print(3 in numbers)
Output will be True.
Example with string:
text = “Python Programming”
print(“Python” in text)
Output will be True.
NOT IN OPERATOR
The not in operator returns True if the specified value does not exist in the sequence.
Example:
numbers = [1, 2, 3, 4, 5]
print(10 not in numbers)
Output will be True.
IDENTITY OPERATORS
Identity operators are used to compare the memory location of two objects. They check whether two variables refer to the same object.
There are two identity operators:
is
is not
IS OPERATOR
The is operator returns True if both variables refer to the same object in memory.
Example:
x = [1, 2, 3]
y = x
print(x is y)
Output will be True because both variables point to the same object.
IS NOT OPERATOR
The is not operator returns True if two variables do not refer to the same object.
Example:
x = [1, 2, 3]
y = [1, 2, 3]
print(x is not y)
Output will be True because both lists are separate objects in memory.
DIFFERENCE BETWEEN EQUALITY AND IDENTITY
The equality operator == checks whether the values are equal.
The identity operator is checks whether the objects are the same in memory.
Example:
x = [1, 2, 3]
y = [1, 2, 3]
print(x == y)
Output will be True
print(x is y)
Output will be False
WHY THESE OPERATORS ARE IMPORTANT
Membership operators help in searching and validating data inside sequences. Identity operators help in understanding how objects are stored in memory.
Mastering membership and identity operators allows you to write more efficient and logically correct Python programs.