How to check if an element is in a list in Python?
Published on Aug. 22, 2023, 12:17 p.m.
To check if an element is in a list in Python, you can use the in
operator. The in
operator returns a Boolean value (True
or False
) indicating whether the element is present in the list.
Here’s an example:
my_list = ['apple', 'banana', 'orange']
if 'banana' in my_list:
print("Yes, 'banana' is in the list")
else:
print("No, 'banana' is not in the list")
Output:
Yes, 'banana' is in the list
In this example, we define a list of fruits and then use the in
operator to check if the element ‘banana’ is present in the list. Since ‘banana’ is indeed present in the list, the program prints “Yes, ‘banana’ is in the list”.
You can also negate the in
operator to check if an element is not in a list:
my_list = ['apple', 'banana', 'orange']
if 'pear' not in my_list:
print("No, 'pear' is not in the list")
else:
print("Yes, 'pear' is in the list")
Output:
No, 'pear' is not in the list
In this example, we use the not in
operator to check if the element ‘pear’ is not present in the list. Since ‘pear’ is not present in the list, the program prints “No, ‘pear’ is not in the list”.