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.
1 2 3 4 5 6 7 8 |
my_list = [1, 2, 3, 4, 5] number_to_check = 3 if number_to_check in my_list: print("The number is present.") else: print("The number is not present.") |
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.
1 2 3 4 5 6 7 8 |
my_list = [1, 2, 3, 4, 5] number_to_check = 3 if my_list.count(number_to_check) > 0: print("The number is present.") else: print("The number is not present.") |
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.
1 2 3 4 5 6 7 8 |
my_list = [1, 2, 3, 4, 5] number_to_check = 3 if any(x == number_to_check for x in my_list): print("The number is present.") else: print("The number is not present.") |
Output:
The number is present.
Full code example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
my_list = [1, 2, 3, 4, 5] # Using 'in' keyword number_to_check = 3 if number_to_check in my_list: print("The number is present.") else: print("The number is not present.") # Using 'list.count()' method if my_list.count(number_to_check) > 0: print("The number is present.") else: print("The number is not present.") # Using 'any()' function with a list comprehension if any(x == number_to_check for x in my_list): print("The number is present.") else: print("The number is not present.") |
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.