Membership
Operators in Python
Master the in and not in operators to check whether values exist inside collections: strings, lists, tuples, and more.
What Are Membership Operators?
Membership operators let you ask a simple yes-or-no question: "Is this value inside that collection?" Python gives you two keywords for this purpose.
Where Can You Use Them?
Membership operators work on any iterable in Python: objects you can loop through one element at a time.
Why Do They Matter?
Without membership operators you would need to write an entire loop every time you want to check if something exists. They make code shorter, faster, and easier to read.
found = False
for item in fruits:
if item == "apple":
found = True
# With membership operator
found = "apple" in fruits
The Syntax Rule
value in sequence # returns True or False
value not in sequence # returns True or False
How Python Searches
For lists and tuples, Python walks through each element left to right, comparing with ==. It stops as soon as it finds a match.
in vs not in
| in | not in | |
|---|---|---|
| Returns True when | Value exists | Value is absent |
| Returns False when | Value is absent | Value exists |
| Alternative Syntax | (value in seq) | not (value in seq) |
| Use case | Validation, filtering | Guarding, exclusion |
How to Apply Them
Example 1: Strings
print("World" in message) # True
print("world" in message) # False
print("xyz" not in message) # True
Example 2: Lists
if "green" in colors:
print("Found green!") # runs
if "yellow" not in colors:
print("No yellow.") # runs
Example 3: Dictionaries
print("name" in student) # True (key)
print("Alice" in student) # False (not a key)
print("Alice" in student.values()) # True (value)
Combining with if/else
word = input("Enter a word: ")
if word.lower() in banned:
print("Blocked!")
else:
print("Allowed.")
Speed Bonus: Sets
Checking membership in a list takes longer as the list grows. Checking membership in a set is almost instant, no matter how large.
if user_id in big_list: # \(O(n)\)
# Fast for large collections
if user_id in big_set: # \(O(1)\)
Membership in Loops
word = "education"
for char in word:
if char in vowels:
print(char, "is a vowel")
# e is a vowel
# u is a vowel
# a is a vowel
# i is a vowel
# o is a vowel
Common Mistakes
Summary Reference
| Collection | in checks | Example | Result |
|---|---|---|---|
| String | Substring | "lo" in "hello" | True |
| List | Element | 5 in [1, 5, 9] | True |
| Tuple | Element | "a" in ("b", "c") | False |
| Set | Element | 2 in {1, 2, 3} | True |
| Dict | Key | "age" in {"age": 16} | True |
Question 1 of 5
What does the following expression evaluate to?
"cat" in "concatenate"
Question 2 of 5
Given d = {"x": 10, "y": 20}, what does 10 in d return?
Question 3 of 5
Which expression correctly checks if "banana" is NOT in a list called fruits?
Question 4 of 5
What does 3 in [1, [2, 3], 4] evaluate to?
Question 5 of 5
Why is checking membership in a set generally faster than in a list?