This post will discuss how to check if a value exists in a Python List.

1. Using In operator

The standard way to find a value in a Python list is with the in operator. This operator can test whether an object is contained within another object, such as a value within a list. This is demonstrated below:

Download  Run Code

 
The code above resulted in True because 3 is an element of the list. Note that the in operator internally calls the __contains__() function:

Download  Run Code

 
This method is easy to use and works for any type of value. It works by scanning through all the elements in the list until it finds the value or end of the list is reached.

2. Using Set

The in operator is no doubt the simplest and the most elegant way to find a value in a list. But if you need to perform multiple lookups, consider converting the list to a set. As lookups in the set are very efficient, you can do this in constant time.

Download  Run Code

3. Using Dictionary

You can also create a dictionary of value-index pairs for doing multiple lookups. This is often useful when you need to find the index of the item as well.

Download  Run Code

 
Alternatively, you can use the get(item, default) function, which returns the item’s index if present; default value otherwise.

Download  Run Code

4. Using count() function

If you want to know the number times a value occurs within a list, you can use the count() function. It can also be used to check if a value exists in a Python list, as follows:

Download  Run Code

5. Using any() function

The any() function checks whether any element of an iterable (such as a list) is True or not. You can use it to check if a value exists in a Python list using a generator expression that iterates through each element of the list and compares it with 3 using the == operator. For example:

Download  Run Code

That’s all about determining whether a value exists in a list in Python.