Python Membership “not in” Operator

Python’s “not in” operator checks negative membership of an object in a collection. It consists of the two reserved keywords in” to test membership of the left operand in the right operand collection, and “not” to logically invert the result. The expression x not in y checks if the object x doesn’t exists in the collection y. Existence is tested using the equality operator ==. You can check membership using the “not in” operator in all collections such as lists, sets, strings, and tuples.

Figure 1: Check negative membership of item 42 in the list of integers.

Checking membership is exemplified in the following code snippet (see Figure 1):

>>> item = 42
>>> my_list = [1, 2, 3, 4, 5, 6]
>>> item not in my_list
True

Here’s another example on strings that shows that capitalization matters for Python string equality:

x = 'alice'
my_list = ['Alice', 'Bob', 'Carl']
print(x not in my_list)
# True

In fact, Python has two membership operators in and not in that test whether a value exists in a collection such as string, list, tuple, set, and dictionary.

OperatorMeaningExample
inTrue if value/variable is found in the sequencex in my_list
not inTrue if value/variable is not found in the sequencex not in my_list
Figure 2: Check positive membership of item 42 in the list of integers.

Video Membership

Python “not in” String

You can check negative membership of a character in a string using the “not in” keyword operator. For example, the expression 'f' not in 'finxter' returns False because the character 'f' exists in the string 'finxter'.

>>> 'f' not in 'finxter'
False

You can also check negative membership of a string in another string using the “not in” operator. For example, the expression 'inx' not in 'finxter' returns False because the string 'inx' exists in the string 'finxter'.

>>> 'inx' not in 'finxter'
False

Python “not in” List

You can check negative membership of an individual object in a list using the “not in” keyword operator. For example, the expression 42 not in [1, 2, 3] returns True because the integer 42 doesn’t exist in the list [1, 2, 3].

>>> 42 not in [1, 2, 3]
True
>>> 'finxter' not in ['finxter', 'learn', 'python']
False

Python “not in” Set

You can check negative membership of an individual object in a set with the “not in” keyword operator. For example, the expression 42 not in {1, 2, 3} returns True because the integer 42 doesn’t exist in the set {1, 2, 3}.

>>> 42 not in {1, 2, 3}
True
>>> 'finxter' not in {'finxter', 'learn', 'python'}
False

Python “not in” Dictionary

You can check negative membership of an individual key in a dictionary with the “not in” keyword operator. For example, the expression 'a' not in {'a': 1, 'b': 2} returns False because the string key exists in the dictionary.

>>> 'a' not in {'a': 1, 'b': 2}
False
>>> 'c' not in {'a': 1, 'b': 2}
True
>>> 43 not in {42: [1, 2], 22: [3, 4]}
True

Python “not in” Range

You can check negative membership of an individual key in a range object with the “not in” keyword operator. For example, the expression 5 not in range(5) returns True because the integer 4 doesn’t exist in the range object with integers 0, 1, 2, 3, 4.

>>> 5 not in range(5)
True
>>> 4 not in range(5)
False

Python “not in” Operator Overloading

Operator overloading replaces the standard meaning of an operator with a customized version. You can overload the “in” and “not in” operators by overriding the __contains__(self, item) method and return a Boolean value True or False whether the item exists in the custom class object or not.

Here’s a generalized example:

class MyClass:
    def __init__(self, my_collection):
        self.my_collection = my_collection

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


my = MyClass('hello world')

print('hello' not in my)
# False

print('hi' not in my)
# True

The custom class MyClass wouldn’t generally support membership. But by defining the __contains__() “dunder” method, you can reduce membership of an object in the class to the problem of checking membership of an object in a collection using the “in” operator. Now, you can check, for example, if a string is a member of a custom class object.

Note: By overriding the magic method __contains__(self, item), your Python class now supports positive and negative membership with the operators “in” and “not in“.

Python “not in” Operator Runtime Complexity

The following table shows the runtime complexities of the “not in” operator for different basic collection data structures with n elements.

Collection TypeRuntime Complexity
listO(n)
setO(1)
dictO(1)
tupleO(n)
stringO(n)
Table: Runtime complexity of checking negative membership for lists, sets, dicts, tuples, and strings with n elements.

Checking positive and negative membership for lists, tuples, and strings has linear runtime complexity. Python iterates over the whole collection and compares the searched element against every single collection element. For large collections, checking membership can become prohibitively expensive.

Checking membership for sets and dictionaries has constant runtime complexity. Python uses a hash table to instantly check if an element is in the set or dict—no matter how large the data structure. Especially for large collections such as n=10000 elements, sets should generally be preferred over lists and tuples.

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!