Python - Check if Element is in List
Python - Check if Element is present in List
You can write a condition to check if an element is present in a list or not using in keyword.
The syntax of condition to check if the element is present in given list is
element in list
The above condition returns True if the element is present in the list. Else, if returns False.
Examples
1. Check if element 'a' is in the given list
In the following program, we will check if element 'a'
is present in list {'a', 'e', 'i', 'o', 'u'}
. We will use the condition specified above along with Python If-Else statement.
Python Program
vowels = {'a', 'e', 'i', 'o', 'u'}
element = 'a'
if element in vowels:
print(element, 'is in the list of vowels.')
else:
print(element, 'is not in the list of vowels.')
Output
a is in the list of vowels.
2. Check if element 'b' is not in the list
You can also check the inverse of the above example. Meaning, you can check if an element is not present in the list.
To write a condition for checking if element is not in the list, use not operator in the syntax as shown below.
element not in list
In the following program, we will check if element 'b'
is not present in list {'a', 'e', 'i', 'o', 'u'}
.
Python Program
vowels = {'a', 'e', 'i', 'o', 'u'}
element = 'b'
if element not in vowels:
print(element, 'is not in the list of vowels.')
else:
print(element, 'is in the list of vowels.')
Output
b is not in the list of vowels.
Summary
In this tutorial of Python Examples, we learned how to check if an element is in list, or if an element is not in list.