How To Check If An Element Is In A List In Python

In this tutorial, we will learn how to check if an element is present in a list using Python programming language.

Python provides various ways to search for specific elements in a list, and we will explore several techniques in this tutorial.

Knowing how to efficiently verify whether an element is in a list can be especially helpful for those who are working with large datasets or data manipulation tasks.

Method 1: The ‘in’ Operator

The simplest and most widely used method in Python for checking if an element exists in a list is by using the in keyword. This method returns True if the element exists in the list, and False otherwise.

Let’s consider the following list of numbers:

Now, to check if the number 7 is in the list, you can use the following code:

The output for this code will be:
True
Similarly, to check if the number 0 is in the list:

The output for this code will be:
False

Method 2: Using the count() Function

Another way to check if an element exists in a list is by using the count() function. The count() function returns the number of occurrences of an element in a list. If the count is greater than 0, that means the element exists in the list.

Let’s consider the same numbers list as before and check if the number 7 exists:

The output for this code will be:

True

Method 3: Using the any() Function and List Comprehension

You can also use the any() function in combination with list comprehension to check whether an element exists in a list. The any() function returns True if at least one of the elements in the given iterable (list, tuple, set, etc.) is True.

Let’s check if the number 7 is in the numbers list using this method:

The output for this code will be:

True

This method can be particularly useful when you want to check for multiple conditions or when you have more complicated criteria for searching elements in a list.

Full Code

True
True
True

Conclusion

In this tutorial, we learned how to check if an element exists in a list using Python. We looked at three different methods: using the in operator, the count() function, and the any() function with list comprehension. These methods can be very helpful in a variety of situations and can be easily applied in your own Python programs.