Open In App

Check if element exists in list in Python

Last Updated : 19 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

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

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

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.

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

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:

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

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.

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

Output
Element 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}")


Previous Article
Next Article

Similar Reads

Python | Check if element exists in list of lists
Given a list of lists, the task is to determine whether the given element exists in any sublist or not. Given below are a few methods to solve the given task. Method #1: Using any() any() method return true whenever a particular element is present in a given iterator. C/C++ Code # Python code to demonstrate # finding whether element # exists in lis
5 min read
Python | Check if a list exists in given list of lists
Given a list of lists, the task is to check if a list exists in given list of lists. Input : lst = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]] list_search = [4, 5, 6] Output: True Input : lst = [[5, 6, 7], [12, 54, 9], [1, 2, 3]] list_search = [4, 12, 54] Output: False Let’s discuss certain ways in which this task is performed. Method #1: Using
4 min read
Python - Test if any set element exists in List
Given a set and list, the task is to write a python program to check if any set element exists in the list. Examples: Input : test_dict1 = test_set = {6, 4, 2, 7, 9, 1}, test_list = [6, 8, 10] Output : True Explanation : 6 occurs in list from set. Input : test_dict1 = test_set = {16, 4, 2, 7, 9, 1}, test_list = [6, 8, 10] Output : False Explanation
4 min read
Check If Value Exists in Python List of Objects
In Python, checking if a specific value exists in a list of objects is a common task. There are several methods to achieve this, and in this article, we will explore five generally used methods with simple code examples. Each method provides a different approach to checking for the existence of a value in a list of objects. To Check If Value Exists
3 min read
Python | Check if tuple exists as dictionary key
Sometimes, while working with dictionaries, there is a possibility that it's keys be in form of tuples. This can be a sub problem to some of web development domain. Let's discuss certain ways in which this problem can be solved. Method #1 : Using in operator This is the most recommended and Pythonic way to perform this particular task. It checks fo
7 min read
Python: Check if a File or Directory Exists
Sometimes the need to check if the folder exists in python, and check whether a directory or file exists becomes important because maybe you want to prevent overwriting the already existing file, or maybe you want to make sure that the file is available or not before loading it. So to check how to check if a Directory Exists without exceptions in P
5 min read
Check if a value exists in a DataFrame using in & not in operator in Python-Pandas
In this article, Let’s discuss how to check if a given value exists in the dataframe or not.Method 1 : Use in operator to check if an element exists in dataframe. C/C++ Code # import pandas library import pandas as pd # dictionary with list object in values details = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age
3 min read
Check if Table Exists in SQLite using Python
In this article, we will discuss how to check if a table exists in an SQLite database using the sqlite3 module of Python. In an SQLite database, the names of all the tables are enlisted in the sqlite_master table. So in order to check if a table exists or not we need to check that if the name of the particular table is in the sqlite_master table or
2 min read
Check if a string exists in a PDF file in Python
In this article, we'll learn how to use Python to determine whether a string is present in a PDF file. In Python, strings are essential for Projects, applications software, etc. Most of the time, we have to determine whether a string is present in a PDF file or not. Here, we'll discuss how to check f a string exists in a PDF file in Python. Here, w
2 min read
Check If a Nested Key Exists in a Dictionary in Python
Dictionaries are a versatile and commonly used data structure in Python, allowing developers to store and retrieve data using key-value pairs. Often, dictionaries may have nested structures, where a key points to another dictionary or a list, creating a hierarchical relationship. In such cases, it becomes essential to check if a nested key exists b
3 min read
Practice Tags :
three90RightbarBannerImg