![]() |
VOOZH | about |
In Python, Membership and Identity operators help us check relationships between values and objects. They are mainly used to test whether a value exists within a sequence or whether two variables refer to same object in memory.
The Membership operators test for the membership of an object in a sequence, such as strings, lists or tuples. Python offers two membership operators to check or validate the membership of a value. They are as follows:
The "in" operator returns True if the given element exists inside a sequence, otherwise it returns False.
True False True
Explanation:
The "not in" operator works the opposite of "in" operator, it returns True if the element is not found in a sequence.
False True False
Explanation:
Python also provides a function from the operator module called contains() that works like in.
Syntax:
operator.contains(sequence, value)
Example: Using operator.contains() with different sequences
True False False False False
Explanation: Works the same as in, but in function form (useful in functional programming).
The Identity Operators are used to compare the objects if both objects are actually of same data type and share same memory location. There are different identity operators such as:
The "is" operator checks if two variables point to the same object (same memory location).
True False True True
Explanation:
The "is not" operator checks if two variables point to different objects.
False True False False
Explanation:
The equality operator (==) is used to compare value of two variables, whereas identity operator (is) is used to compare memory location of two variables.
Example: In this code we have two lists that contains same data, we used 'is' operator and '==' operator to compare both lists.
False True
Explanation:
Mutable objects (list, dict, set) always create new objects, so "is" operator between identical-looking containers always returns False.
Immutable objects (str, tuple, small integers) may reuse memory, so "is" can sometimes return True depending on Python's implementation.