How To Check If A List Contains A Number In Python

In this tutorial, we will learn how to check if a list contains a number in Python. Python, a feature-rich and widely used programming language, offers various built-in methods to accomplish this task.

We will explore some of these methods to efficiently check if a specific number exists in the list, and in the end, we will try out the code provided to solidify your understanding.

Step 1: Using the in keyword

The in keyword is one of the easiest and most straightforward methods to check if a list contains a certain element. It returns True if the specified element is present in the list, and False otherwise.

Output:
The number is present.

Step 2: Using the list.count() method

The list.count() method returns the number of occurrences of a specific element in a list. If the count is greater than zero, the element is present in the list; otherwise, it is not.

Output:
The number is present.

Step 3: Using the any() function with a list comprehension

The any() function checks if any element of an iterable (like a list) is True. By combining it with a list comprehension, we can check if any element in the list matches the specified number.

Output:
The number is present.

Full code example

Output

The number is present.
The number is present.
The number is present.

Conclusion

By following the steps mentioned above, we can easily check if a list contains a number in Python using various methods like the in keyword, the list.count() method, and the any() function with a list comprehension. Each method has its own advantages and use cases, so you can choose the one that best fits your needs.