Sitemap
99spaceidea

99spaceidea

Welcome to 99SPACEIDEA, a vibrant online platform dedicated to providing a boundless realm of creative inspiration

How to Check if Two Elements are in a Python List

2 min readJun 19, 2023

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.

Press enter or click to view image in full size

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 in operator can be used with any iterable object, such as a list, a tuple, or a string.
  • The in operator 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.

--

--

99spaceidea
99spaceidea

Written by 99spaceidea

Welcome to 99SPACEIDEA, a vibrant online platform dedicated to providing a boundless realm of creative inspiration