This concise, example-based article will walk you through 3 different ways to check whether a Python list contains an element. There’s no time to waste; let’s get started!
Using the “in” operator
This solution uses the in
operator to check if an element is in a list. It returns True
if the element is found and False
otherwise.
# define a list with different data types
my_list = [1, 2, 3, ['a', 'b', 'c'], {'sling': 'academy'}]
print(2 in my_list) # True
print(['a', 'b', 'c'] in my_list) # True
print({'sling': 'academy'} in my_list) # True
print('turtle' in my_list) # False
The code is concise and intuitive. It also works for any type of element, even if they are not hashable or mutable.
Using the list.index() method
This solution uses the index()
method to find the index of the first occurrence of an element in a list. It returns the index as an integer if the element is found and raises a ValueError
exception otherwise.
Example:
# define a list with different data types
my_list = [1, 2, 3, ['a', 'b', 'c'], {'sling': 'academy'}]
try:
index = my_list.index(3)
print(f"'3' found at index {index}")
except ValueError:
print('Value not found in list')
Output:
'3' found at index 2
This approach requires handling a potential exception, but it provides information about the index of the element in the list (if found).
Using the list.count() method
Another working solution is to use the list.count()
method to count the occurrences of an element in a list and check if it’s greater than zero.
Example:
my_list = [1, 2, 3, 4, 5, 3, 4, 3, 3]
element = 3
count = my_list.count(element)
if count > 0:
print(f'Element {element} is in the list {count} times')
else:
print(f'Element {element} is not in the list')
Output:
Element 3 is in the list 4 times
If the list is large, this approach is less efficient than the preceding ones because it requires traversing the entire list to count occurrences.