Here are five ways to check if a list contains an element in Python:
- Using in operator
- Using list comprehension
- Using list.count()
- Using any()
- Using not in operator
Visual representation
Method 1: Using “in” operator
The in operator checks whether the list contains a specific element and returns True if the element is found, and False if it is not.
Visual Representation
Example
list = [1, 2, 3, 4, 5]
if 3 in list:
print("3 found in List : ", list)
else:
print("The element does not exist in the list")
Output
3 found in List : [1, 2, 3, 4, 5]
Let’s take an example where we do not find an item on the list.
list = [1, 2, 3, 4, 5]
if 6 in list:
print("3 found in List : ", list)
else:
print("The list does not contain an element")
Output
The list does not contain an element
Method 2: Using list comprehension
The all() function returns True if all elements of the given iterable evaluate to True. This function can be effectively combined with list comprehension and the “in” operator to check if a list contains all specified elements.
Visual Representation
main_list = [1, 2, 3, 4, 5]
check_list = [2, 4]
if all([item in main_list for item in check_list]):
print("The list contains all the elements")
else:
print("The list does not contain all elements")
Output
The list contains all the elements
Method 3: Using list.count()
The count() method returns the number of times the specified element appears in the list. If it’s greater than 0, a given item exists in the list.
Example
list = [1, 2, 3, 4, 5]
if list.count(4) > 0:
print("4 found in List : ", list)
Output
4 found in List : [1, 2, 3, 4, 5]
Method 4: Using any()
The any() function checks if any element in an iterable meets a specified condition. It returns True as soon as it finds an element that satisfies the condition; otherwise, it is False.
Example
data_string = "The last season of Game of Thrones was not good"
main_list = ['Stranger Things', 'Squid Game', 'Game of Thrones']
print("The original string : " + data_string)
print("The original list : " + str(main_list))
res = any(item in data_string for item in main_list)
print("Does string contain 'Game of Thrones' list element: " + str(res))
Output
The original string : The last season of Game of Thrones was not good
The original list : ['Stranger Things', 'Squid Game', 'Game of Thrones']
Does string contain 'Game of Thrones' list element: True
Method 5: Using not in operator
The not in operator evaluates to True if the specified element is not in the list, and False otherwise.
Visual Representation
Example
list = [1, 2, 3, 4, 5]
print(7 not in list)
print(3 not in list)
Output
True
False
Conclusion
The best and most efficient way to check if a list contains an element is to use the in operator.
בנימין שמיד
Grate post!
Thank you so much!