The not in operator tests that a value is absent from a container. x not in container returns True when x is not found and False when it is, and it is exactly equivalent to not (x in container). It works with lists, tuples, sets, dictionaries (keys), strings, ranges and any object that supports membership testing.
Python documents in and not in as membership test operators. They are comparison operators, so they have the same precedence as == and <.
not in worksnot in with each built-in type
__contains__not in worksThe expression a not in b calls the membership protocol of b. For built-in containers that means b.__contains__(a); if that method is missing, Python falls back to iterating b and comparing items with ==. The result is then inverted.
Prefer x not in items over not x in items. They behave the same, but the first form reads naturally and is what linters and PEP 8 recommend.
not in with each built-in typeLists and tuples are scanned item by item, so the check is O(n).
Sets use hashing, so membership tests take O(1) time on average. For repeated lookups in a big collection, convert a list to a set first.
For a dictionary, not in checks keys, never values:
For strings, not in tests for a substring:
range supports constant-time membership tests for integers.
A comprehension with not in removes unwanted items. Use a set for the exclusions so each check is fast:
For this specific pattern, config.setdefault("log_level", "INFO") does the same in one call.
__contains__You can make in and not in work for your own types by defining __contains__:
If a class defines only __iter__ or __getitem__, Python falls back to scanning it, which is slower.
not in is case-sensitive for strings. Normalize both sides, or use all() and any() for several values:
not in on a dictionary and expecting it to check values.if x not in a or b:. This parses as (x not in a) or b. Write if x not in a and x not in b: or if x not in (a, b) for a tuple of options.not in on a large list inside a loop. That makes the loop O(n squared); use a set.is not when you mean not in. is not compares identity, not membership.[1] not in {1, 2}, which raises TypeError.not in and !=?!= compares two values for inequality, while not in checks whether a value is missing from a collection.
not in the same as not x in y?Yes, they give the same result. The not in form is the preferred style.
not in in a conditional expression or comprehension?Yes. It returns a plain Boolean, so it works in if, while, assert, comprehensions and conditional expressions.
not in in my own class?Define __contains__(self, item) on the class. Python then uses it for both in and not in.
not in is Python's membership operator for absence: it returns True when a value is not in a list, tuple, set, dictionary key set, string or range. Pick the container type for performance (sets for many lookups), remember that dictionaries check keys, and use it to avoid duplicates, filter data and set defaults.