Membership Operators
3 min read ·
Membership operators in Python are used to test whether a value exists inside a sequence or collection.
They are commonly used with strings, lists, tuples, sets, and dictionaries.
Python provides two membership operators:
innot in
What Are Membership Operators?
Membership operators check presence or absence of a value in a container.
They always return a Boolean value:
True or False.Membership Operators Table
| Operator | Description |
|---|---|
in | Returns True if value exists in the sequence |
not in | Returns True if value does not exist in the sequence |
Membership Operators with Strings
Checks if a substring or character exists in a string.
Membership Operators with Lists
Checks if an element exists in a list.
Membership Operators with Tuples
Membership Operators with Sets
Sets are optimized for fast membership checks.
Membership Operators with Dictionaries (Tricky)
Membership checks in dictionaries work on keys, not values.
Checking Values Explicitly
Membership Operators in if Conditions
Membership Operators with Nested Collections
Case Sensitivity in Membership
Membership checks are case-sensitive.
Performance Insight (Important)
inon sets and dictionaries is faster than lists- Lists require linear search
- Sets and dicts use hashing
Common Mistakes
Mistake 1: Assuming Dictionary Checks Values
This checks keys, not values ❌
Mistake 2: Expecting Partial Match in Lists
This returns
False.Practice
- Check if a word exists in a sentence
- Validate email using membership operators
- Check presence of a key in a dictionary
- Compare membership performance between list and set