Wednesday, December 25, 2024
Google search engine
HomeLanguagesCheck if element exists in list in Python

Check if element exists in list in Python

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.

Python3




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")


Output

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].

Python3




# 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.

Python3




# 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().

Python3




# 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()

Python3




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.”

Python3




# 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")


Output

Checking 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.

Python3




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")


Output

Yes, 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:

Python3




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


Output

True
False


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.

RELATED ARTICLES

Most Popular

Recent Comments