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: Returns True if the specified value is found in the sequence.
  • not in: Returns True if 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.

# Check for a number in a list numbers = [10, 20, 30, 40, 50] result = 20 in numbers print(result) # Output: True # Check for a string in a list fruits = ["apple", "banana", "cherry"] result = "orange" in fruits print(result) # Output: False
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.

# Check for a single character greeting = "hello world" result = "w" in greeting print(result) # Output: True # Check for a substring result = "world" in greeting print(result) # Output: True
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.

# Check for an item in a tuple permissions = ("read", "write", "execute") result = "read" in permissions print(result) # Output: True
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.

# Check that a number is not in a list numbers = [10, 20, 30, 40, 50] result = 100 not in numbers print(result) # Output: True # Check that a string is not in a list fruits = ["apple", "banana", "cherry"] result = "apple" not in fruits print(result) # Output: False
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.

# Check for a missing character message = "Python is fun" result = "z" not in message print(result) # Output: True # Check for a missing substring result = "java" not in message print(result) # Output: True
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 Exercises

How 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 } # Check if 'username' is a key key_exists = "username" in user_profile print(key_exists) # Output: True # Check if 'email' is a key key_missing = "email" not in user_profile print(key_missing) # Output: True
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 } # Check if the value 'alex' exists value_exists = "alex" in user_profile.values() print(value_exists) # Output: True
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.")
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 (Simulated as 'a' for this example) choice = "a" # 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.")
# 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"] # Create a new list containing only the fruits from all_products fruit_products = [product for product in all_products if product in fruits] print(fruit_products) # Output: ['apple', 'banana', 'orange', 'grape']
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.

# Inefficient for large lists large_list = list(range(1000000)) is_present = 999999 in large_list # This can be slow print("Found in list:", is_present) # Much more efficient large_set = set(large_list) is_present = 999999 in large_set # This is very fast print("Found in set:", is_present)
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:

  1. Define a list of banned_items containing "knife", "explosive", and "poison".
  2. Define a variable backpack_item with the value "knife".
  3. Use in to check if the backpack_item is in the banned_items list.
# TODO: Create banned_items list # banned_items = ... # TODO: Create backpack_item # backpack_item = ... # TODO: Check if item is in list # is_banned = ... # print(is_banned)
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
📝

Next Lesson

Continue with the next lesson on Python Bitwise Operators.

Next Lesson ->
Scroll to Top