Python – Check if Element is in List

Python – Check if Element is present 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.

Example 1: Check if Element is in 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.')
Run

Output

a is in the list of vowels.

Example 2: Check if Element is not in 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.')
Run

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.