Python Membership Operators
In this page:
What Are Membership Operators?
Membership operators test whether a value exists inside a container like a list, tuple, string, set, or dictionary, returning a plain True or False without needing a manual loop. They read almost like English, which is one of the reasons Python code checking for membership is so concise and readable.
Example: What Are Membership Operators?
fruits = ["apple", "banana"]
print("apple" in fruits)
in and not in
The in operator returns True if the left-hand value is found inside the right-hand container, and not in is its exact opposite. Both work across every built-in sequence and collection type, making them one of the most broadly reusable operators in the language.
Example: in and not in
fruits = ["apple", "banana"]
print("apple" in fruits)
print("kiwi" not in fruits)
Membership in Strings
For strings, in performs a substring search rather than checking individual characters only, so cat in concatenate returns True because that exact sequence of letters appears inside the larger string. This makes it a quick way to check for substrings without calling a separate method.
Example: Membership in Strings
print("cat" in "concatenate")
Membership in Dictionaries
When used on a dictionary, in checks against the dictionary's keys by default, not its values — name in my_dict tests whether name is a key, so checking for a value requires in my_dict.values() explicitly. This trips up beginners who expect it to search values.
Example: Membership in Dictionaries
user = {"name": "Alex", "age": 30}
print("name" in user)
print("Alex" in user.values())
How in Connects to __contains__
Under the hood, in calls the container's __contains__ method if one is defined, which is why custom classes can support membership testing by implementing that dunder method themselves. For objects without __contains__, Python falls back to iterating and comparing each element.
Example: How in Connects to __contains__
class MyBox:
def __init__(self, items):
self.items = items
def __contains__(self, item):
return item in self.items
box = MyBox([1, 2, 3])
print(2 in box)
Chapter Quiz — Complete all 16 topics to unlock
0/16 topics done
Complete these topics first:
- Python print()
- Python input()
- Python Format Strings
- Python f-strings
- Python String Formatting
- Python Arithmetic Operators
- Python Relational Operators
- Python Logical Operators
- Python Bitwise Operators
- Python Assignment Operators
- Python Increment & Decrement
- Python Ternary Operator
- Python Operator Precedence
- Python Identity Operators
- Python Membership Operators
- Python Operators