Python
Programming
Lists
Code Examples
Python Tips

How to check if something is not in a list in Python

Codemia Knowledge Hub ·

Use the not in operator: if x not in items:. It returns True when no element of the list is equal to x. Two things affect whether the check is correct and fast: how your values compare for equality, and whether a list (linear scan) or a set (hash lookup) holds them.

Basic syntax

python
1items = ["apple", "banana", "orange"]
2
3if "grape" not in items:
4    print("Add grape to list")

The operator returns True if no equal element exists in the sequence.

Case-insensitive checks

String membership is case-sensitive, so "alice" is not found in a list containing "Alice". When your rules are case-insensitive, normalize both the source and the query:

python
1names = ["Alice", "Bob", "Carla"]
2query = "alice"
3
4if query.lower() not in {n.lower() for n in names}:
5    print("Not found (case-insensitive)")

List vs set performance

Membership in a list is linear (O(n)), while set membership is average constant time (O(1)):

python
1blocked_list = [f"user{i}" for i in range(100000)]
2blocked_set = set(blocked_list)
3
4user = "user99999"
5print(user not in blocked_list)  # slower for large data
6print(user not in blocked_set)   # faster

If you run many checks, especially in a hot path, convert the list to a set once and check against that.

Custom objects and equality

Membership relies on equality (__eq__), and on hashing (__hash__) for sets. Instances of a custom class do not compare by value unless you implement __eq__, and a bad implementation makes the check wrong:

python
1class Item:
2    def __init__(self, id):
3        self.id = id
4    def __eq__(self, other):
5        return isinstance(other, Item) and self.id == other.id
6
7items = [Item(1), Item(2)]
8print(Item(2) not in items)  # False

Mixing incompatible types, such as searching a list of integers for the string "2", means in never finds a match and not in is always True, which hides the real bug.

Guard clauses

not in works well for defensive early exits:

python
1def process_status(status: str) -> None:
2    allowed = {"pending", "running", "done"}
3    if status not in allowed:
4        raise ValueError(f"Invalid status: {status}")

This keeps validation concise and readable. Avoid mutating a collection while you iterate over it and check membership in it at the same time.

Validating code that relies on these checks

A correct snippet is only the start when a membership check guards real input. Decide what "working" means before you call it done: one correctness measure (for example, output agreement with known-good fixtures), one performance measure (for example, p95 runtime under expected load), and, if retries are involved, one reliability measure such as failure rate.

Keep a short executable checklist in version control and run it in CI where possible: validate environment assumptions, run a minimal happy-path example, run one malformed-input case, and confirm the logs carry enough context for troubleshooting. If external systems are involved, add a dry-run mode that exercises integration paths without destructive actions. A typical validation flow:

bash
1# Example validation flow
2make test
3make lint
4./scripts/smoke_check.sh

Also make ownership explicit: who responds when the component fails, what alert threshold triggers an investigation, and what fallback is acceptable, such as disabling a feature flag or reverting one deployment. Finally, document what the approach handles and what it does not try to solve, so it is not misused later.


Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms