← Back to Python Course | Chapter 2: Input, Output & Operators | Lesson 15 of 16

Python Membership Operators

What Are Membership Operators?

Membership operators test whether a value exists inside a container like a list, tuple, string, set, or dictionary, returning a plain True or False without needing a manual loop. They read almost like English, which is one of the reasons Python code checking for membership is so concise and readable.

Example: What Are Membership Operators?

python
fruits = ["apple", "banana"]
print("apple" in fruits)

in and not in

The in operator returns True if the left-hand value is found inside the right-hand container, and not in is its exact opposite. Both work across every built-in sequence and collection type, making them one of the most broadly reusable operators in the language.

Example: in and not in

python
fruits = ["apple", "banana"]
print("apple" in fruits)
print("kiwi" not in fruits)

Membership in Strings

For strings, in performs a substring search rather than checking individual characters only, so cat in concatenate returns True because that exact sequence of letters appears inside the larger string. This makes it a quick way to check for substrings without calling a separate method.

Example: Membership in Strings

python
print("cat" in "concatenate")

Membership in Dictionaries

When used on a dictionary, in checks against the dictionary's keys by default, not its values — name in my_dict tests whether name is a key, so checking for a value requires in my_dict.values() explicitly. This trips up beginners who expect it to search values.

Example: Membership in Dictionaries

python
user = {"name": "Alex", "age": 30}
print("name" in user)
print("Alex" in user.values())

How in Connects to __contains__

Under the hood, in calls the container's __contains__ method if one is defined, which is why custom classes can support membership testing by implementing that dunder method themselves. For objects without __contains__, Python falls back to iterating and comparing each element.

Example: How in Connects to __contains__

python
class MyBox:
    def __init__(self, items):
        self.items = items
    def __contains__(self, item):
        return item in self.items

box = MyBox([1, 2, 3])
print(2 in box)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.