How to Check if Two Elements are in a Python List
In Python, you can check if two elements are in a list using the in operator. The in operator returns True if the specified element is found in the list, and False if it is not found.
For example, the following code will check if the elements 1 and 2 are in the list list_of_numbers:
Python
list_of_numbers = [1, 2, 3, 4, 5]if 1 in list_of_numbers and 2 in list_of_numbers:
print("The elements 1 and 2 are in the list")
else:
print("The elements 1 and 2 are not in the list")In this example, the if statement will only be executed if the elements 1 and 2 are found in the list list_of_numbers. If the elements are not found in the list, the else statement will be executed.
Get 99spaceidea’s stories in your inbox
Join Medium for free to get updates from this writer.
You can also use the in operator to check if one element is in a list, and then check if another element is in the list. For example, the following code will check if the element 1 is in the list list_of_numbers, and then check if the element 3 is in the list.
Python
list_of_numbers = [1, 2, 3, 4, 5]if 1 in list_of_numbers:
if 3 in list_of_numbers:
print("Both elements are in the list")
else:
print("The element 3 is not in the list")
else:
print("The element 1 is not in the list")In this example, the if statement will only be executed if the element 1 is found in the list list_of_numbers. If the element 1 is not found in the list, the else statement will be executed. The if statement will then check if the element 3 is found in the list. If the element 3 is found in the list, the print statement will be executed. If the element 3 is not found in the list, the else statement will be executed.
Here are some additional things to keep in mind when checking if two elements are in a Python list:
- The
inoperator can be used with any iterable object, such as a list, a tuple, or a string. - The
inoperator is a very efficient way to check if an element is in a list.
I hope this article helps you understand how to check if two elements are in a Python list.








