In this tutorial, we will introduce how to check if an element is not in a list in Python.
not in to Check if an Element Is Not in a List in Python
in keyword in Python can be used to check whether an element is present in a collection or not. If an element is present, then it returns
True; otherwise, it returns
False. For example:
x = 3 in [1,2,5] y = 1 in [1,2,5] print(x) print(y)
If we need to check if an element is not in the list, we can use the
not in keyword. The
not is a logical operator to converts
False and vice-versa. So if an element is not present in a list, it will return
x = 3 not in [1,2,5] print(x)
__contains__ Method of the List to Check if an Element Is Not in a List in Python
In Python, we have magic functions that are associated with classes and are not to be meant invoked directly although it is possible. One such function called
__contains__ can be used to check if an element is present in a list or not. For example,
x = [1,2,5].__contains__(1) print(x) x = [1,2,5].__contains__(3) print(x)
Although this method works, it is not advisable to use this method since magic functions are not intended to be invoked directly.