Check Element Not in a List in Python

  1. Use not in to Check if an Element Is Not in a List in Python
  2. Use the __contains__ Method of the List to Check if an Element Is Not in a List in Python

In this tutorial, we will introduce how to check if an element is not in a list in Python.

Use not in to Check if an Element Is Not in a List in Python

The 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)

Output:

False
True

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 True to False and vice-versa. So if an element is not present in a list, it will return True.

x = 3 not in [1,2,5]
print(x)

Output:

True

Use the __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)

Output:

True
False

Although this method works, it is not advisable to use this method since magic functions are not intended to be invoked directly.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python List

  • Multiply Two Lists in Python
  • Convert Two Lists Into Dictionary in Python