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 exist in the collection y.

If you want to check if a specific item, such as “Python”, is not in a list in Python, you can use the not in operator. Here’s an example:

my_list = ["Java", "C++", "JavaScript"]

if "Python" not in my_list:
    print("Python is not in the list.")
else:
    print("Python is in the list.")

In this example, the program checks if “Python” is not in the list my_list. If it’s not in the list, it prints “Python is not in the list.”. Otherwise, it prints “Python is in the list.”.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading