The list is an important container in Python as it stores elements of all the data types as a collection. Knowledge of certain list operations is necessary for day-day programming. This article discusses the Fastest way to check if a value exists in a list or not using Python.
Example
Input: test_list = [1, 6, 3, 5, 3, 4]
3 # Check if 3 exist or not.
Output: True
Explanation: The output is True because the element we are looking is exist in the list.
Check if an element exists in a list in Python
Check if an element exists in the list using the “in” statement
In this method, one easily uses a loop that iterates through all the elements to check the existence of the target element. This is the simplest way to check the existence of the element in the list. Python is the most conventional way to check if an element exists in a list or not. This particular way returns True if an element exists in the list and False if the element does not exist in the list. The list need not be sorted to practice this approach of checking.
Python
lst=[ 1, 6, 3, 5, 3, 4 ]
#checking if element 7 is present
# in the given list or not
i=7
# if element present then return
# exist otherwise not exist
if i in lst:
print("exist")
else:
print("not exist")
Time Complexity: O(1)
Auxiliary Space: O(n), where n is the total number of elements.
Find if an element exists in the list using a loop
The given Python code initializes a list named test_list
with some integer elements. It then iterates through each element in the list using a for
loop. Inside the loop, it checks if the current element i
is equal to the value 4 using an if
statement. If the condition is true, it prints “Element Exists” to the console. The code will output the message if the number 4 is present in the list, and in this case, “Element Exists” will be printed since the number 4 exists in the list [1, 6, 3, 5, 3, 4]
.
Python
# Initializing list
test_list = [1, 6, 3, 5, 3, 4]
# Checking if 4 exists in list
for i in test_list:
if(i == 4):
print("Element Exists")
Output:
Element Exists
Time Complexity: O(n)
Auxiliary Space: O(1)
Check if an element exists in the list using any() function
It achieves this by utilizing the any()
function with a generator expression. The generator expression iterates through each element test_list
and checks if it appears more than once in the list. The result of this check is stored in the variable result
. Finally, the code prints a message indicating whether there are any duplicate elements, displaying “Does string contain any list element: True” if duplicates exist and “Does string contain any list element: False” if there are no duplicates.
Python
# Initializing list
test_list = [1, 6, 3, 5, 3, 4]
result = any(item in test_list for item in test_list)
print("Does string contain any list element : " +str(bool(result)))
Output:
Does string contain any list element : True
Find if an element exists in the list using the count() function
We can use the in-built Python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List. Demonstrating to check the existence of elements in the list using count().
Python
# Initializing list
test_list = [10, 15, 20, 7, 46, 2808]
print("Checking if 15 exists in list")
# number of times element exists in list
exist_count = test_list.count(15)
# checking if it is more than 0
if exist_count > 0:
print("Yes, 15 exists in list")
else:
print("No, 15 does not exists in list")
Output:
Checking if 15 exists in list
Yes, 15 exists in list
Check if an element exists in the list using sort with bisect_left and set
Converting the list into the set and then using it can possibly be more efficient than only using it. But having efficiency as a plus also has certain negatives. One among them is that the order of the list is not preserved, and if you opt to take a new list for it, you would require to use extra space. Another drawback is that set disallows duplicity and hence duplicate elements would be removed from the original list. In the conventional binary search way of testing element existence, hence list has to be sorted first and hence does not preserve the element ordering. bisect_left() returns the first occurrence of the element to be found and has worked similarly to lower_bound() in C++ STL.
Note: The bisect function will only state the position of where to insert the element but not the details about if the element is present or not.
Demonstrating to check existence of element in list using set() + in and sort() + bisect_left()
Python
from bisect import bisect_left ,bisect
# Initializing list
test_list_set = [ 1, 6, 3, 5, 3, 4 ]
test_list_bisect = [ 1, 6, 3, 5, 3, 4 ]
print("Checking if 4 exists in list ( using set() + in) : ")
# Checking if 4 exists in list
# using set() + in
test_list_set = set(test_list_set)
if 4 in test_list_set :
print ("Element Exists")
print("Checking if 4 exists in list ( using sort() + bisect_left() ) : ")
# Checking if 4 exists in list
# using sort() + bisect_left()
test_list_bisect.sort()
if bisect_left(test_list_bisect, 4)!=bisect(test_list_bisect, 4):
print ("Element Exists")
else:
print("Element doesnt exist")
Output:
Checking if 4 exists in list ( using set() + in) :
Element Exists
Checking if 4 exists in list ( using sort() + bisect_left() ) :
Element Exists
Check if an element exists in list using find() method
The given Python code checks if the number 15 exists in the list test_list
. It converts the elements of the list to strings and concatenates them with hyphens. Then, it uses the find()
method to check if the substring “15” exists in the resulting string. If “15” is found, it prints “Yes, 15 exists in the list”; otherwise, it prints “No, 15 does not exist in the list.”
Python
# Initializing list
test_list = [10, 15, 20, 7, 46, 2808]
print("Checking if 15 exists in list")
x=list(map(str,test_list))
y="-".join(x)
if y.find("15") !=-1:
print("Yes, 15 exists in list")
else:
print("No, 15 does not exists in list")
OutputChecking if 15 exists in list
Yes, 15 exists in list
Check if element exists in list using Counter() function
The provided Python code uses the Counter
class from the collections
module to calculate the frequency of each element in the test_list
. It then checks if the frequency of the number 15 is greater than 0. If the frequency is non-zero, it means “15” exists in the list, and the code prints “Yes, 15 exists in the list.” Otherwise, it prints “No, 15 does not exist in the list.” The Counter
class efficiently counts element occurrences, allowing for a straightforward existence check.
Python
from collections import Counter
test_list = [10, 15, 20, 7, 46, 2808]
# Calculating frequencies
frequency = Counter(test_list)
# If the element has frequency greater than 0
# then it exists else it doesn't exist
if(frequency[15] > 0):
print("Yes, 15 exists in list")
else:
print("No, 15 does not exists in list")
OutputYes, 15 exists in list
Find if an an element exists in list using try-except block
One additional approach to check if an element exists in a list is to use the index() method. This method returns the index of the first occurrence of the element in the list or throws a ValueError if the element is not present in the list. To use this method, you can wrap the call to index() in a try-except block to catch the ValueError and return False if it occurs:
Python
def element_exists(lst, element):
# Try to get the index of the element in the list
try:
lst.index(element)
# If the element is found, return True
return True
# If a ValueError is raised, the element is not in the list
except ValueError:
# Return False in this case
return False
#Test the function
test_list = [1, 6, 3, 5, 3, 4]
print(element_exists(test_list, 3)) # prints True
print(element_exists(test_list, 7)) # prints False
#This code is contributed by Edula Vinay Kumar Reddy
Time complexity: O(n), where n is the length of the list. The index() method iterates through the list to find the element, so the time complexity is linear.
Space complexity: O(1). This approach does not require any additional space.
Find if an an element exists in list using filter() Function
Step-by-Step Approach
- Define the list my_list and Set element_to_check.
- Use the filter() function to create an iterator (filtered_elements) that contains elements equal to the element_to_check.
- Convert the iterator filtered_elements to a list.
- This step is necessary as the filter() function returns an iterator. The list now contains elements equal to element_to_check.
- Check if the list filtered_list is not empty.
- If the list is not empty, it means the element exists in the original list.
Python
my_list = [1, 2, 3, 4, 5]
element_to_check = 3
# Use filter to create an iterator of elements equal to the target element
filtered_elements = filter(lambda x: x == element_to_check, my_list)
# Convert the iterator to a list and check if it's not empty
if list(filtered_elements):
print("Element exists in the list")
else:
print("Element does not exist in the list")
OutputElement exists in the list
Time Complexity: O(n)
Auxiliary Space Complexity: O(n)
Check if element exists in list in Python – FAQs
How to check if a value exists in a list of lists in Python?
To check if a value in a list exists within a string in Python, you can iterate through the list and use the in keyword to check if each element is present in the string. Here’s how you can do it:
my_list = ['apple', 'banana', 'cherry']
my_string = "I like apples and bananas."
for item in my_list:
if item in my_string:
print(f"{item} is found in the string.")
else:
print(f"{item} is not found in the string.")
How to check if a value in a list is in a string Python?
We can use the in keyword to check if an element exists in a list.
my_list = [1, 2, 3, 4, 5]
value = 3
if value in my_list:
print(f"{value} found in the list")
else:
print(f"{value} not found in the list")
How to check if a value exists in a dictionary of lists in Python?
We can use the in keyword to check if a key exists in the dictionary and then use in again to check if the value exists in the list associated with that key.
dict_of_lists = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
value = 5
exists = any(value in lst for lst in dict_of_lists.values())
Here, exists will be True if value exists in any list within dict_of_lists, otherwise False.
How to check if value is in list pandas?
We can use the isin() method in pandas to check if a value exists in a DataFrame column or Series.
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3, 4, 5]})
value = 3
if value in df['A'].values:
print(f"{value} found in the DataFrame")
else:
print(f"{value} not found in the DataFrame")
How to check the type of a value in a list in Python?
Use the type() function to check the type of a value at a specific index or use list comprehensions to check types across the entire list.
my_list = [1, 'apple', 3.14, True]
index = 1
value_type = type(my_list[index])
print(f"Type of element at index {index}: {value_type}")
# Check types across the entire list
types = [type(item) for item in my_list]
print(f"Types in the list: {types}")
Please Login to comment...