Python: Checking If An Element Is NOT PRESENT In The Given List (Or Other Collection Types)

In this article, let us see how to check if an element is absent in a data structure such as lists, tuples, etc.

In Python, a list can contain up to 536,870,912 items in a 32-bit system, which means it can be pretty difficult to know if it contains a certain item or not.

To deal with this, Python gives us a pretty convenient solution, enter the ‘not in’ operator. 

The ‘not in’ operator

The ‘not in’ operator is used to check if a specific element is present in a data structure or not. For example, we can use it to see if a particular item exists in a list, or a set, or a tuple, or a dictionary!

The syntax is pretty simple:

<element> not in <data structure>

The ‘not in’ operator returns True if an element exists in a data structure, and it returns False otherwise:

In other words, if it returns True it means that <element> does NOT exist in <data structure>. If it exists, the ‘not in’ operator returns False.

Let’s put that to the test:

my_list = [1,2,3,4,5]

print(5 not in my_list)
print(10 not in my_list)
False
True

Since it returns boolean values, it can be used alongside the if statement to do more things!

Here is a very simple example:

my_list = ["a", "b", "c", "d", "e"]

if "f" not in my_list:
    print("The letter 'f' is not in my_list!")
else:
    print("The letter 'f' is present in my_list")
The letter 'f' is not in the list!

If you wish to learn how the not in operator does this magic we have an entire article dedicated to it, which you can find in the link below!

Python “in” and “not in”: Explained Using Examples!

In the above program, we had a small list of letters called my_list. We then checked if the letter ‘f’ was an element in my_list and printed a message to the user appropriately. And here’s the syntax for that:

if <element> not in <data structure>:
    #do something

Now lets see some examples of using the ‘not in’ operator with all the following data structures

  1. Lists
  2. Sets
  3. Tuples
  4. Dictionaries

Let’s start by looking at how we can check the membership of an element in a List.

Example#1: Checking if an element is NOT PRESENT in a given LIST

The following program checks if an entered color is a part of the primary colors group or not:

primary_colors = ["red", "yellow", "blue"]

color = input("Please enter a primary color: ")

if color not in primary_colors:
    print(f"{color} is not a primary color!")
else:
    print(f"{color} is a part of the primary colors group!")

Here’s a breakdown of what’s happening:

  • We have a list of primary colors stored in the list named primary_colors
  • The user enters a color which is stored in the variable color
  • We then use an if statement to confirm if color is not present in primary_colors
  • Depending on the if statement, either the if-block or the else-block is executed.

This is the output we will get if we enter anything other than the 3 primary colors:

Please enter a primary color: pink
pink is not a primary color!

And this is the output when we enter a primary color:

Please enter a primary color: yellow
yellow is a part of the primary colors group!

If you wish to check the membership of a given item in more than one collection at the same instant, be sure to check out the following video we made on a related topic!

Let’s move on to the next example and see how we can check the membership of an element in a set.

Example#2: Checking if an element is NOT PRESENT in a given SET

The method to use ‘not in’ with sets is the same as that of lists as we just saw.

Consider this set that has the ingredients to make a smoothie:

smoothie_ingredients = {"banana", "strawberry", "milk", "yogurt"}

Here’s an item which I’m not sure this is part of the recipe or not:

item = "butter"

Let’s run it with the ‘in’ operator to check if it is contained in the ingredients list:

if item not in smoothie_ingredients:
    print(f"{item} is not needed to make a smoothie!")
else:
    print(f"Yes! We need {item} to make a smoothie!")
butter is not needed to make a smoothie!

Looks like we got our answer!

Let’s move on to the next example and see how we can check the membership of an element in a dictionary.

Example#3: Checking if an element is NOT PRESENT in a given DICTIONARY‘S KEYS

We can check if keys exist in a dictionary or not by using the ‘not in’ operator, pretty much the same way as we did with lists.

We have a simple dictionary my_dict:

my_dict = {"a":"apple", "b":"ball", "c":"cat"}

Whenever we use ‘not in’ to find something in dictionaries, it must be noted that the operator only searches this in the keys of the dictionary. It does NOT search the values of the dictionary. 

As we know, the keys in this dictionary are “a”, “b”, and “c”. 

So if we try to search for the key “d” using ‘not in’:

print("d" not in my_dict)

We get True as there is no key called “d” in my_dict:

True

Let’s move on to the next example and see how we can check the membership of an element in a dictionary’s values.

Example#4: Checking if an element is NOT PRESENT in a given DICTIONARY‘S VALUES

Let’s continue with the previous example:

>>> print("cat" not in my_dict.values())
False
>>> print("dog" not in my_dict.values())
True

Here we used the values() method of the dictionary object to get a list of values and again used the not in operator to figure out if the element is part of the dictionary or not.

Let’s move on to the next example and see how we can check the membership of an element in a tuple.

Example#5: Checking if an element is NOT PRESENT in a given TUPLE

Here we have a tuple named prime_nums containing prime numbers under 20:

prime_nums = (2, 3, 5, 7, 11, 13, 17, 19)

We ask the user to enter a prime number under 20:

num = int(input("Can you enter a prime number under 20: "))

The following if statement checks if num is an item inside the tuple prime_nums:

if num not in prime_nums:
    print("That is not a prime number!")
else:
    print("Good job! That is a prime number!")

We can see depending on what we enter, we get different outputs:

Can you enter a prime number under 20: 16
That is not a prime number!
Can you enter a prime number under 20: 13
Good job! That is a prime number!

Pretty simple right?

And with that, I will end this article.

Congratulations on making it to the end of the article, not many have the perseverance to do so!

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Checking if element is present in the list (or other collection types) in Python

If-Else in Python: Explained with Examples!

Python if with 3 conditions: Explained with Examples!

If with multiple “and” conditions in Python: Explained With Examples

If with multiple “or” conditions in Python: Explained with Examples

Figuring out if “break” was used to exit the loop in Python

Python “if” Statement with Multiple Conditions: Explained with Examples!

Python: “if not true” How to write? Explained with Examples!

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn