Coding

Not in Python: How the not in Operator Works (With Examples)

In Python, not in is the membership operator that returns True when a value is absent from a container. 4 not in [1, 2, 3] is True, and "z" not in "eggs" is also True.

The operator works on lists, tuples, sets, dictionaries, strings and any other container that supports in. The Python language reference defines it simply: "The operator not in is defined to have the inverse truth value of in." Lines starting with >>> below show example output you can reproduce in a Python prompt.

Basic syntax of not in

The form is x not in y. It evaluates to True if x is not a member of y, and to False if it is.

>>> colors = ["red", "green", "blue"]
>>> "yellow" not in colors
True
>>> "red" not in colors
False

It is most often used in an if statement to act only when something is missing:

allowed = ["admin", "editor"]
role = "guest"

if role not in allowed:
    print("Access denied")

Both in and not in have the same priority as the comparison operators (==, <, is and so on), according to the built-in types documentation. For the full list of operator types, see Python operators explained.

not in with a list or tuple

For lists and tuples, not in compares the value against each item in turn. The sequence operations table in the docs says x not in s is "False if an item of s is equal to x, else True".

>>> 4 not in (1, 2, 3)
True
>>> [1, 2] not in [[1, 2], [3, 4]]
False
>>> 1 not in [[1, 2], [3, 4]]
True

The last line is a common surprise. The list contains two inner lists, not the number 1, so 1 is not a member. Membership checks only the top level of the container. It does not search inside nested items.

not in with a string

For strings, not in tests for a substring, not just a single character. The docs show "gg" in "eggs" as True, and describe the string test as true if and only if x is a substring of y. So not in is true when the text does not appear anywhere.

>>> "gg" not in "eggs"
False
>>> "ham" not in "eggs"
True
>>> "EGG" not in "eggs"
True

The match is case-sensitive, so "EGG" is not found in "eggs". To ignore case, lower both sides first: "egg" not in text.lower().

One edge case from the reference: empty strings are always considered a substring of any other string. So "" in "abc" is True, and "" not in "abc" is False. If the value you test might be empty, for example user input, check for that first, or you will get an answer that looks wrong.

not in with a dictionary

On a dictionary, in tests whether the dictionary has a given key. So not in tests that a key is missing.

>>> prices = {"apple": 1.2, "pear": 0.9}
>>> "plum" not in prices
True
>>> "apple" not in prices
False
>>> 0.9 not in prices
True
>>> 0.9 not in prices.values()
False

The third test is True because 0.9 is a value, not a key. Use .values() when you want to look at values. A typical use of the key test is to set a default only when the key is missing:

if "plum" not in prices:
    prices["plum"] = 2.0

not in with a set

Sets support the same operator. Sets hold unique items, so they are a natural fit when you only care about presence, for example a list of IDs you have already processed:

>>> seen = {10, 20, 30}
>>> 40 not in seen
True
>>> 20 not in seen
False
for item_id in [10, 40, 20, 50]:
    if item_id not in seen:
        seen.add(item_id)
        print("new:", item_id)

This prints new: 40 and new: 50, and leaves the set holding five values.

not x in y versus x not in y

You can also write not x in y. It gives the same answer, because not inverts the result of x in y. The reference describes not as returning True if its argument is false, and always returning a bool.

>>> not 4 in [1, 2, 3]
True
>>> 4 not in [1, 2, 3]
True

Prefer x not in y. It is the form the language provides for this test, and it reads as one operator instead of two words that could be misread as (not x) in y. That misreading is wrong, as not binds less tightly than in, but the single operator removes the doubt.

not in versus is not

These look similar and do different jobs.

OperatorQuestion it answersExample
not inIs the value absent from the container?"a" not in ["b", "c"]
is notAre these two names pointing at different objects?result is not None
!=Are these two values unequal?count != 0

Use is not for singletons such as None. Use not in for containers. To compare against several values at once, test against a collection instead of chaining != with and:

if status != "done" and status != "failed" and status != "skipped":
    ...

if status not in ("done", "failed", "skipped"):
    ...

Both blocks mean the same thing. The second is shorter and the list of values is in one place.

How Python decides: identity first, then equality

For built-in containers such as list, tuple, set, frozenset, dict and collections.deque, the reference says x in y is equivalent to any(x is e or x == e for e in y). Each item is checked for identity first and equality second. This only matters for objects that are not equal to themselves, such as float("nan"):

>>> nan = float("nan")
>>> nan == nan
False
>>> nan not in [nan]
False
>>> float("nan") not in [float("nan")]
True

In the second test the list holds the very same object, so the identity check succeeds even though == says false. In the last test the two NaN values are different objects, so neither check succeeds and not in reports the value as missing.

not in with your own classes

A class controls the operator by defining __contains__(). The reference describes the fallback order: if __contains__() is missing but __iter__() is defined, Python iterates and looks for a matching item. If that is missing too but __getitem__() is defined, it tries non-negative integer indexes until it finds a match or hits IndexError. not in then returns the opposite of whatever in found.

class Inventory:
    def __init__(self, items):
        self._items = set(items)

    def __contains__(self, item):
        return item in self._items

>>> stock = Inventory(["bolt", "nut"])
>>> "washer" not in stock
True

You do not define a separate method for not in. Defining __contains__() is enough.

Common mistakes with not in

  • Expecting it to search nested data. 1 not in [[1, 2]] is True. Flatten the data or loop through the inner lists.
  • Testing dictionary values with the dictionary itself. x not in d checks keys. Use d.values() for values.
  • Forgetting that string tests are case-sensitive substring tests. "cat" not in "concatenate" is False, because "cat" appears inside the longer word. If you need whole-word matching, split the text into words first and test against the resulting list.
  • Writing if x not in y or z: and expecting z to be part of the membership test. It parses as (x not in y) or z. Write if x not in (y, z): or use parentheses to show what you mean.
  • Writing is not in. No such operator exists, and it is a syntax error. Use not in for containers and is not for identity.

Before relying on a check against user input, remember the empty-string rule above, and test the edge cases with a short script.

Frequently asked questions

What is the difference between not in and is not in Python?
There is no operator called is not in. The operator not in tests membership in a container, as in 4 not in [1, 2, 3]. The separate operator is not tests object identity, as in value is not None. Mixing the two up is a syntax error or a wrong result.
Is not x in y the same as x not in y?
They give the same result. The reference defines not in as the inverse truth value of in, and not applied to x in y also inverts it. The form x not in y is the idiomatic one and reads better, because the negation sits next to the operator it negates.
Does not in work on a dictionary?
Yes, and it tests keys, not values. 'a' not in {'a': 1} is False. To test values, use a not in d.values().
Can not in be used in an if statement with several values?
Yes. Put the values in a tuple, list or set and test against it: if status not in ('done', 'failed'):. This replaces a chain of != comparisons joined with and.

Sources