Skip to content

Python not in list

  • by

Use not in operator to Check if an Element Is Not in a List in Python. or you can use Use the __contains__ Method of the List to Check if an Element Is Not in a List in Python.

Python is not in list

Simple example code. 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)

list1 = [1, 2, 3]
res = 3 not in list1
print("Not in list: ", res)

Output:

Python not in list

Use the contains Method

Check if an element is present in a list or not.

x  = [1,2,5].__contains__(1)
print(x)
x  = [1,2,5].__contains__(3)
print(x)

Output:

True
False

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.

Do comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *