Python Membership Operators (in, not in)
What Are Membership Operators?
A membership operator in Python checks if a value exists within a sequence. It helps you answer questions like "Is this number in my list?" or "Does this character appear in my string?" You can write clean, readable code without needing a loop for a simple check. For example, the expression 'a' in 'apple' quickly confirms the letter is there.
The two membership operators are:
in: ReturnsTrueif the specified value is found in the sequence.not in: ReturnsTrueif the specified value is not found in the sequence.
Want to write efficient Python checks? This lesson is part of our Free Python course covering operators, lists, performance and more.
Explore this free Python course →1. The 'in' Operator
The in operator returns True if a value exists in a sequence and False otherwise. It's a simple and direct way to confirm an item's presence.
Use in with a List
You can check if an element is part of a list.
numbers = [10, 20, 30, 40, 50]
result = 20 in numbers
print(result)
fruits = ["apple", "banana", "cherry"]
result = "orange" in fruits
print(result)
Your output will appear here...
Use in with a String
The operator can also check for a character or a substring within a larger string.
greeting = "hello world"
result = "w" in greeting
print(result)
result = "world" in greeting
print(result)
Your output will appear here...
Use in with a Tuple
Membership checks work the same way for tuples as they do for lists.
permissions = ("read", "write", "execute")
result = "read" in permissions
print(result)
Your output will appear here...
2. The 'not in' Operator
The not in operator does the opposite of in. It returns True if a value does not exist in a sequence. This is useful for verifying an item's absence.
Use not in with a List
You can confirm that an element does not exist in a list.
numbers = [10, 20, 30, 40, 50]
result = 100 not in numbers
print(result)
fruits = ["apple", "banana", "cherry"]
result = "apple" not in fruits
print(result)
Your output will appear here...
Use not in with a String
This operator can verify the absence of a character or substring.
message = "Python is fun"
result = "z" not in message
print(result)
result = "java" not in message
print(result)
Your output will appear here...
You're making great progress! Ready to apply these operators in real-world scenarios?
Take Python ExercisesHow Membership Operators Work with Dictionaries
When you use membership operators with a dictionary, they check the keys by default, not the values. Remember this rule because it's a common source of bugs for new developers.
Checking for Keys
To see if a key exists, use the operator directly on the dictionary.
user_profile = {
"username": "alex",
"level": 5,
"active": True
}
key_exists = "username" in user_profile
print(key_exists)
key_missing = "email" not in user_profile
print(key_missing)
Your output will appear here...
Checking for Values
To check if a value exists in a dictionary, you must explicitly search the dictionary's values using the .values() method.
user_profile = {
"username": "alex",
"level": 5,
"active": True
}
value_exists = "alex" in user_profile.values()
print(value_exists)
Your output will appear here...
Practical Use Cases
You can combine membership operators with other Python features like if statements and list comprehensions to solve common problems.
Conditional Logic with if Statements
The most common use is controlling program flow with an if statement. This lets you execute code only if a certain condition is met.
allowed_users = ["alice", "bob", "charlie"]
current_user = "bob"
if current_user in allowed_users:
print("Access granted.")
else:
print("Access denied.")
Your output will appear here...
Input Validation
You can use in to validate user input against a list of acceptable options.
# Get user input
choice = input("Choose an option (a, b, c): ")
# Validate the choice
valid_options = ["a", "b", "c"]
if choice in valid_options:
print(f"You selected option {choice}.")
else:
print("Invalid option selected.")
Your output will appear here...
Filtering Data
Membership operators are useful for filtering one sequence based on the contents of another. A list comprehension provides a concise way to do this.
all_products = ["apple", "banana", "orange", "grape", "broccoli"]
fruits = ["apple", "banana", "orange", "grape"]
fruit_products = [product for product in all_products if product in fruits]
print(fruit_products)
Your output will appear here...
Performance Considerations
The performance of a membership check depends on the data type. Performance means how long it takes to find an item, especially in a large collection.
- Lists and Tuples: Checking for an item has a time complexity of
O(n). This means the search time grows linearly with the size of the sequence because Python may have to check every element. - Sets and Dictionaries: Checking for an item in a set or a dictionary key has an average time complexity of
O(1). This means the time is constant, regardless of the sequence size, because these types use a hash table for fast lookups.
If you need to perform many membership checks on a large collection, convert it to a set first. The initial conversion takes time, but later lookups will be much faster.
large_list = list(range(1000000))
is_present = 999999 in large_list
large_set = set(large_list)
is_present = 999999 in large_set
Your output will appear here...
Final Challenge: Security Check
Create a security checkpoint script.
Your Task:
- Define a list of
banned_itemscontaining "knife", "explosive", and "poison". - Define a variable
backpack_itemwith the value "knife". - Use
into check if thebackpack_itemis in thebanned_itemslist.
banned_items = ["knife", "explosive", "poison"]
backpack_item = "knife"
is_banned = backpack_item in banned_items
print(is_banned)
Your output will appear here...
Lesson Completed
You have successfully learned about Python Membership Operators (in, not in), how they work with lists, strings, and dictionaries, and their performance differences.
Full Python Course
Master Python with 11+ hours of content, 50+ exercises, and real-world projects.
Enroll Now