Check if element exists in list in Python
Given a list, our task is to check if an element exists in it.
Examples:
Input: lst = [10, 20, 30, 40, 50], element = 30
Output: Element exists in the listInput: lst = [10, 20, 30, 40, 50], element = 60
Output: Element does not exist in the list
Python provides multiple methods to perform this check depending on the use cases, some of them are discussed below:
Using in Statement
Python provides an 'in' statement that checks if an element is present in an iterable or not.
a = [10, 20, 30, 40, 50]
if 30 in a:
print("Element exists in the list")
else:
print("Element does not exist")
Output
Element exists in the list
Explanation: Returns True if the element is present, otherwise False.
Using a loop
We can iterate over the list using a loop and check if the element is present in it or not.
a = [10, 20, 30, 40, 50]
key = 30
flag = False
for val in a:
if val == key:
flag = True
break
if flag:
print("Element exists in the list")
else:
print("Element does not exist")
Output
Element exists in the list
Explanation:
- "for loop" helps iterate over each element and "if condition" compares it with target value
- flag is used to determine whether else condition gets executed or not.
Note: This method is less efficient than using 'in'.
Using any() Function
any() checks if a specific element exists in a list and returns True if found, otherwise False.
a = [10, 20, 30, 40, 50]
flag = any(x == 30 for x in a)
if flag:
print("Element exists in the list")
else:
print("Element does not exist")
Output
Element exists in the list
Explanation:
- any(x == 30 for x in a): Checks each element in the list a to see if it equals 30. returns true if any element matches.
- flag: Stores the result (True if 30 is found, otherwise False).
Using count()
count() function checks how many times a specific element appears in a list and returns the number of occurence.
a = [10, 20, 30, 40, 50]
if a.count(30) > 0:
print("Element exists in the list")
else:
print("Element does not exist")
Output
Element exists in the list
Explanation:
- a.count(30): Counts how many times 30 appears in the list a.
- if a.count(30) > 0: Checks if the count is greater than 0, meaning the element exists.