What Are Membership Operators in Python?
Membership operators in Python are used to test whether a value exists within a sequence (such as a list, tuple, string, set, or dictionary keys). The result of a membership test is a Boolean value — True if the value is found, and False if it is not found.
Types of Membership Operators
Python supports two membership operators:
| Operator | Meaning |
|---|---|
in | Returns True if the value exists in the sequence |
not in | Returns True if the value does not exist in the sequence |
Membership with Strings
text = "Hello, Python!" print("Python" in text) print("Java" in text) # Output: # True # FalseHere, "Python" is a substring of the string text, so "Python" in text is True. "Java" is not present, so it’s False.
Membership with Lists
fruits = ["apple", "banana", "cherry"] print("banana" in fruits) print("grape" not in fruits) # Output: # True # True"banana" is in the list, and "grape" is not, so the membership tests yield True.
Membership with Tuples
nums = (1, 2, 3, 4) print(3 in nums) print(5 not in nums) # Output: # True # TrueMembership works the same way with tuples as with lists.
Membership with Sets
letters = {"a", "b", "c"} print("b" in letters) print("z" not in letters) # Output: # True # TrueSets support fast membership lookups because they are implemented as hash tables.
Membership with Dictionaries
By default, in checks whether a value is in the keys of a dictionary.
student = {"name": "Alice", "age": 25} print("name" in student) print("Alice" in student) # Output: # True # FalseTo check dictionary values, use:
print("Alice" in student.values())Why Use Membership Operators?
Membership operators are useful when you need to:
-
Check if a value exists before acting
-
Avoid errors when accessing elements
-
Filter or validate input
-
Write readable conditional code
Membership in Conditional Statements
ages = [18, 20, 25] if 20 in ages: print("20 is in the list!") # Output: # 20 is in the list!This evaluates the membership test and executes code accordingly.