Membership and Identity Operators in Python
Python provides two special types of operators:
- Membership Operators: Test whether a value is part of a sequence (such as string, list, tuple, or set).
- Identity Operators: Compare the memory locations of two objects.
These operators help write clean, readable, and efficient code when checking for existence or object identity.
1. Membership Operators
| Operator | Description |
|---|---|
in | Returns True if a value is present in a sequence |
not in | Returns True if a value is NOT present in a sequence |
Example 1: Using in with a List
membership_in_list.py
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)output.txt
TrueExample 2: Using not in with a String
membership_not_in_string.py
sentence = "Python is fun"
print("Java" not in sentence)output.txt
TrueExplanation:
inchecks if the value is in the sequence (string, list, tuple, set, or dictionary keys).not inchecks if the value is absent.
2. Identity Operators
| Operator | Description |
|---|---|
is | Returns True if two variables point to the same object in memory |
is not | Returns True if two variables do NOT point to the same object |
Example 1: Using is with Variables
identity_is.py
x = [1, 2, 3]
y = x
print(x is y)output.txt
TrueExplanation:
ypoints to the same object asx.iscompares identity, not just value.
Example 2: is not with Separate Objects
identity_is_not.py
x = [1, 2, 3]
y = [1, 2, 3]
print(x is not y)output.txt
TrueExplanation:
- Even though
xandyhave the same value, they are different objects. - Their identity (memory location) is different.
Example 3: Using is with Immutable Objects (Integers)
identity_integers.py
a = 100
b = 100
print(a is b)output.txt
TrueExplanation:
- For small integers (typically between
-5and256), Python caches objects. - So
aandbmay point to the same object.
Example 4: is with Strings
identity_strings.py
s1 = "hello"
s2 = "hello"
print(s1 is s2)output.txt
TrueExplanation:
- Short string literals are often cached by Python.
ismay returnTruefor such strings.
Summary
-
Membership Operators:
in: Checks if a value exists in a sequence.not in: Checks if a value does not exist.
-
Identity Operators:
is: Checks if two references point to the same object.is not: Checks if they do not.
-
Use cases:
- Membership: Useful for searching within collections.
- Identity: Useful for checking object identity (especially when working with mutable objects, None, or singleton patterns).