Check Element Not in a List in Python

Manav Narula Jan 05, 2023 Feb 07, 2021
  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
Check Element 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.

Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python List