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

In this article, let us see how to check if an element is present in a data structure such as lists, tuples, etc. with the help of some interesting examples!

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 ‘in’ operator. 

The ‘in’ operator

The ‘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> in <data structure>

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

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

print(5 in my_list)
print(10 in my_list)

If you wish to learn how the 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!

Since it returns boolean values, it can be paired with the if statement to do some pretty cool things!

So for example, if you wanted to do something after you check if an item existed in a list, here’s how you would go about it:

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

if "e" in my_list:
    print("The letter 'e' exists in the list!")
    print("There is no letter 'e' in the list!")
There is no letter 'e' in the list!

In the above example, we have our list my_list, and we try to check if the element ‘e’ exists in the list or not. Depending on the result the if statement gets, either the if-block or the else-block is executed.

And here’s the syntax for that:

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

Now let’s go through using the ‘in’ operator for the following data structures:

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

Checking if an element is present in the given List

This is a simple example that checks for items in the fridge:

fridge_items = ["Eggs", "Milk", "Cheese"]

item = input("Please enter your item: ")

if item in fridge_items:
    print(f"{item} is there in your fridge!")
    print(f"{item} is not there in your fridge!")

We can get different outputs depending on what item we wish to check:

Please enter your item: Yogurt
Yogurt is not available in your fridge!

In this scenario, the ‘in’ operator checks if the item ‘Yogurt’ is in fridge_items and returns False. So the else-block is executed.

Please enter your item: Milk
Milk is available in your fridge!

This time, the ‘in’ operator checks if the item ‘Milk‘ is in fridge_items and returns True. So the if-block is executed.

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!

Checking if an element is present in the given Set

To use ‘in’ when dealing with sets, we pretty much do the same thing we did with lists.

Consider this set that has the ingredients to make banana muffins:

ingredients = {"Milk","Flour","Sugar","Eggs", "Banana", “Butter”}

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

item = "Chocolate"

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

if item in ingredients:
    print(f"{item} is part of the recipe!")
    print(f"{item} is not a part of the recipe!")
Chocolate is not a part of the recipe!

Looks like we got our answer!

Checking if an element is present in the given Dictionary’s Keys

We can check if keys exist in a dictionary or not by using the ‘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 ‘in’ to find something in dictionaries, it must be noted that the operator only searches for 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”:

>>> print("d" in my_dict)
>>> print("a" in my_dict)

Checking if an element is present in the given Dictionary’s Values

If we wish to check if an item is present in the values part of a given dictionary, we can use the method shown in the example below.

>>> print("cat" in my_dict.values())
>>> print("dog" in my_dict.values())

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

Checking if an element is present in the given Tuple

Lastly, let’s look at an example with tuples this time.

multiples_of_4 = (4, 8, 12, 16, 20)

x = int(input("Please enter a number under 20: ")

if x in multiples_of_4:
    print(f"{x} is a multiple of 4")
    print(f"{x} is not a multiple of 4")
>> Please enter a number under 20: 14
14 is not a multiple of 4

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

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