W3docs

Python 'not in': Check if an Item Is Not in a List

Use Python's not in operator to check if an item is missing from a list, string, dict, or set. Covers if not in, is not vs not in, any()/all(), and set speed.

Tags

To check if a value is not in a list in Python, use the not in operator: x not in my_list returns True when x is missing from the list and False when it is present. It is the exact opposite of in, and you will usually see it inside an if statement (if x not in my_list:).

fruits = ["apple", "banana", "cherry"]

print("mango" not in fruits)   # True
print("apple" not in fruits)   # False

in and not in are Python's membership operators. The sections below show both, then cover strings, dictionaries, sets, checking several items at once, case-insensitive checks, performance, and common mistakes (including the is not vs not in mix-up).

In Python, you can check if an item is in a list using the in keyword. For example:

Check if an item is in a list using the in keyword

python— editable, runs on the server

This will print "3 is in the list" because the number 3 is in the list.

Similarly, you can check if an item is not in a list using the not in keyword. For example:

Check if an item is not in a list using the not in keyword

python— editable, runs on the server

This will print "5 is not in the list" because the number 5 is not in the list.

You can also use any() function with a generator expression to check if any of the elements of the list matches the given criteria, which can be any valid expression, this is useful if you want to check if the list contains a particular string, for example:

Check if an item is in a list using the any function

python— editable, runs on the server

This will print "banana is in the list".

Note that these methods will work for lists, tuples, sets, and other iterable objects as well.

Add an item only if it is not already in the list

The most common real-world use of if ... not in is avoiding duplicates: append a value only when the list does not contain it yet.

seen = ["apple", "banana"]

for fruit in ["banana", "cherry", "apple", "kiwi"]:
    if fruit not in seen:
        seen.append(fruit)

print(seen)  # ['apple', 'banana', 'cherry', 'kiwi']

If you only need unique values and do not care about order, a set does this for you. To clean up a list that already has duplicates, see removing list duplicates.

x not in y vs not x in y

Both forms give the same result, because in is evaluated before not. Prefer x not in y: it reads like English, makes the intent obvious, and style checkers such as pycodestyle (rule E713) flag the not x in y form.

colors = ["red", "green"]

print("blue" not in colors)       # True  (recommended style)
print(not "blue" in colors)       # True  (same result, less readable)

not in vs is not

These two look similar but answer different questions:

  • not in is a membership test: "is this value missing from the collection?"
  • is not is an identity test: "are these two names pointing to different objects?" It is mostly used as x is not None.
value = None
items = [1, 2, 3]

print(value is not None)   # False -> identity: value IS the None object
print(value not in items)  # True  -> membership: None is not an element of items

So, to check whether something is missing from a list, use not in, never is not.

not in with strings, dictionaries, sets, and tuples

not in works on any container, but what it searches depends on the type:

# Strings: substring check
print("cat" not in "concatenate")   # False ("cat" is a substring)

# Dictionaries: checks KEYS, not values
ages = {"alice": 30, "bob": 25}
print("carol" not in ages)          # True
print(30 not in ages)               # True  (30 is a value, not a key)
print(30 not in ages.values())      # False (search the values explicitly)

# Sets and tuples work the same way as lists
print(4 not in {1, 2, 3})           # True
print("x" not in ("x", "y"))        # False

Check if several items are not in a list

Combine not in with all() or any() (or a list comprehension) to test multiple values at once:

my_list = [1, 2, 3, 4]

# True only if NONE of the values are in the list
print(all(x not in my_list for x in [5, 6]))   # True

# True if AT LEAST ONE value is missing from the list
print(any(x not in my_list for x in [3, 9]))   # True

# Which values are missing?
print([x for x in [3, 9, 10] if x not in my_list])   # [9, 10]

Case-insensitive "not in" check

String comparisons are case-sensitive, so "alice" is not considered equal to "Alice". Normalize both sides first, with lower() or the more thorough casefold():

names = ["Alice", "Bob", "Carol"]

print("alice" not in names)                          # True  (case differs)
print("alice" not in [n.lower() for n in names])     # False
print("ALICE".casefold() not in {n.casefold() for n in names})  # False

Performance: list vs set

For a list (or tuple), not in has to compare the value against the elements one by one, so in the worst case it checks every element: O(n). For a set or dictionary keys, Python uses a hash table, so the check takes roughly constant time on average: O(1).

import timeit

big_list = list(range(100_000))
big_set = set(big_list)

print(timeit.timeit(lambda: -1 not in big_list, number=1_000))
print(timeit.timeit(lambda: -1 not in big_set, number=1_000))

The exact numbers depend on your machine, but the set lookup is typically thousands of times faster here. If you run many membership checks against the same large collection, convert it to a set once and reuse it. Building the set is itself O(n), and set elements must be hashable (no lists or dicts inside), so for a single check on a small list, plain not in is fine.

Common pitfalls

  • Using is not instead of not in. is not compares object identity, not membership (see above).
  • Expecting a dict to search its values. x not in my_dict only checks keys; use my_dict.values() to search values.
  • Looking for a sub-list. [1, 2] not in [1, 2, 3] is True, because Python looks for the list [1, 2] as a single element, not as a run of elements. Use all() as shown above to check each item.
  • Forgetting about case. "apple" not in ["Apple"] is True; normalize case first if that is not what you want.
  • Slow checks in loops. Repeated not in checks against a big list inside a loop can be slow; use a set instead.

To learn more about working with lists, see the Python Lists chapter and Python if...else for conditional statements.