What Are Membership Operators in Python?

Membership operators in Python are used to test whether a value exists within a sequence (such as a list, tuple, string, set, or dictionary keys). The result of a membership test is a Boolean valueTrue if the value is found, and False if it is not found.

Types of Membership Operators

Python supports two membership operators:

OperatorMeaning
inReturns True if the value exists in the sequence
not inReturns True if the value does not exist in the sequence

Membership with Strings

Python
text = "Hello, Python!" print("Python" in text) print("Java" in text) # Output: # True # False

Here, "Python" is a substring of the string text, so "Python" in text is True. "Java" is not present, so it’s False.

Membership with Lists

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

"banana" is in the list, and "grape" is not, so the membership tests yield True.

Membership with Tuples

Python
nums = (1, 2, 3, 4) print(3 in nums) print(5 not in nums) # Output: # True # True

Membership works the same way with tuples as with lists.

Membership with Sets

Python
letters = {"a", "b", "c"} print("b" in letters) print("z" not in letters) # Output: # True # True

Sets support fast membership lookups because they are implemented as hash tables.

Membership with Dictionaries

By default, in checks whether a value is in the keys of a dictionary.

Python
student = {"name": "Alice", "age": 25} print("name" in student) print("Alice" in student) # Output: # True # False

To check dictionary values, use:

Python
print("Alice" in student.values())

Why Use Membership Operators?

Membership operators are useful when you need to:

  • Check if a value exists before acting

  • Avoid errors when accessing elements

  • Filter or validate input

  • Write readable conditional code

Membership in Conditional Statements

Python
ages = [18, 20, 25] if 20 in ages: print("20 is in the list!") # Output: # 20 is in the list!

This evaluates the membership test and executes code accordingly.