Membership Operators in Python

Check if a value exists within a sequence

What Are Membership Operators?

Membership operators are used to test whether a value is present in a sequence (like a list, tuple, set, string, or dictionary).

Operator Table

Operator Description Example
in Returns True if a value is found in the sequence 'a' in 'apple' → True
not in Returns True if a value is NOT found in the sequence 5 not in [1, 2, 3] → True

Examples

# Strings
word = "hello"
print("h" in word)      # True
print("z" not in word)  # True

# Lists
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)        # True
print("grape" not in fruits)    # True

# Tuples
nums = (1, 2, 3)
print(2 in nums)                # True

# Sets
letters = {'a', 'b', 'c'}
print('d' in letters)           # False

# Dictionaries (checks keys)
info = {"name": "John", "age": 55}
print("name" in info)           # True
print("John" in info.values())   # True

Best Practices

Real-World Example

banned_words = {"bad", "ugly", "hate"}

comment = "I hate this product!"
if any(word in comment.lower() for word in banned_words):
    print("Comment contains inappropriate content!")