How to Find Elements in a List in Python

Many situations involve searching for a specific element inside a collection like searching for a user’s data inside a database and in processes like performing data filtering or validation. A list stores all kinds of data types inside it. An element can be searched inside a list in various ways, such as using the find() method, any() method, count() function, and so on. 

How to Find Elements in a List in Python?

Before diving into how an element can be searched inside a Python list, let us have a better understanding of what lists are.

A list contains each element as a collection. Changes can be made in the list as the programmer wants. Elements inside the list can be of different data types. Python proves to be the most effective language for finding an element inside a list. Some of the methods for finding elements in a List are:

  1. Using “in” Statement 
  2. Using find() method
  3. Using sort with bisect_left 
  4. Using any() function
  5. Using Counter() function
  6. Using count() function
  7. Using try-except block

Let us now discuss the methods that can be used to search elements in a list in detail.

Method 1: Find Elements in a Python List Using “in” Statement

An “in” statement is used to check out each element inside the list using a loop that iterates through each element There is no need to sort while using the in statement. The following code explains how an element can be searched in a list using the “in” statement:

testlist = [3, 5, 5, 8, 9, 20]
def check_element(i):
    if i in testlist:
        print(f"List has the required element {i}.")
    else:
        print(f"The list does not have the desired element {i}.")
check_element(6)
check_element(5)
check_element('A')

In the above code,

  • A sample “testlist” is defined that contains different integers.
  • A function “check_element” is defined.
  • The code works by using the in keyword and interacting through each element in the list.
  • The function is called upon different inputs to see if they exist in the list or not.

Output

The following output explains how an element can be found in the list using the in keyword:

Find Elements in a List in Python 0

Method 2: Find Elements in a Python List Using any() Function

The Python function any() can be used to find an element inside a list. It is used along with a generator statement that checks whether an element is in the “testlist” or not. The following code explains how any() function in Python can be used to search out an element inside a list:

testlist = ['ford', 46, 63, 75, 3, 'chevy']
def check_element(i):
    if any(element == i for element in testlist):
        print(f"List has the required element {i}.")
    else:
        print(f"The list does not have the desired element {i}.")
check_element('chevy') 
check_element(7)
check_element(3)

In the above code,

  • A sample heterogeneous test list is defined.
  • A function “check_element” is defined that will tell if an element exists in the list or not.
  • The function any() checks if there is any one element in the test list that is equivalent to i.
  • It will print if the list contains the element.
  • The function is called on different inputs.

Output

The following output shows how any() function can be used to find an element in a list in Python:

Find Elements in a List in Python 1

Method 3: Find Elements in a Python List Using find() and map() method

The map() function can be used to convert the data type inside the list to a string. The join() function concatenates the resultant string values with hyphens and finally, the find() function gives information about the existence of an element inside a list. The following code explains how the Python functions find(), map(), and join() can be used together to search out an element inside a list:

testlist = ['A', 'C', 'B', 4, 5, 6]
def check_element(i):
    a = list(map(str, testlist))
    b = "-".join(a)
    if b.find(str(i)) != -1:
        print(f"List has the required element {i}.")
    else:
        print(f"The list does not have the desired element {i}.")
check_element(6)
check_element(3)
check_element('A')

In the above code,

  • A sample “testlist” is defined which contains different values of letters and numbers. 
  • A function “check_element()” is defined that takes an element “i”.
  • a stores the map() function converts each element inside the test list to a string which convert to a list
  • The join function joins the elements in the list “a” with hyphens and stores them in the variable “b”.
  • The condition “b.find(str(i)) != -1” checks whether the string representation of “i” is included in b and if it is equal to -1 this means the element does not exist in b.
  • The function is called on different inputs..

Output

The following output displays how an element can be found in a list using find() and map() methods in Python:

Find Elements in a List in Python 2

Method 4: Find Elements in a Python List Using enumerate()

The enumerate() function gives information about the index of an element inside a list. If the function is successful in finding the index, the list has the item. The following code explains how the enumerate() function in Python can be used to search for an element inside a list:

testlist = [34, 56, 53, 65, 63, 62]
def check_element(i):
    for index, element in enumerate(testlist):
        if element == i:
            print(f"The element {i} exists at index {index} in the list")
            return
    print(f"The element {i} doesn't exist in the list") 
check_element(63)
check_element(60)

In the above code,

  • A sample test list with different integers is defined
  • A function check_element is defined that takes an argument i.
  • A for loop operates in the test list using the enumerate() function. 
  • If the element is equal to “i” it will print the element along with its index.
  • The function is checked for different inputs.

Output

The following output displays how enumerate() can be used to find an element in a list in Python:

Find Elements in a List in Python 3

Method 5: Find Elements in a Python List Using sort() With bisect_left and bisect 

The bisect module contains the Python functionalities bisect_left and bisect. These functionalities can be used to get information about an item’s existence inside a list when used with sort().The list has to be given a proper order first which is unwanted. The following code explains how to know whether an element exists in the list or not using the sort() method along with the functionalities from the bisect module:

from bisect import bisect_left ,bisect
testlist = [68, 73, 56, 34]
def check_element(i):
    testlist.sort()
    if bisect_left(testlist, i) != bisect(testlist, i): 
        print(f"List has the required element {i}.")
    else :
        print(f"The list does not have the desired element {i}.")
check_element(73)
check_element(23)

In the above code,

  • The bisect_left and bisect functions are imported from the bisect module.
  • A sample “testlist” is defined that contains different integers.
  • The sort() function does the binary search so that the “testlist” is sorted in ascending order. 
  • The function bisect functionalities return the index where the element is to be inserted.
  • If the result of the bisect_left and bisect function varies, this means that the element is in the list and if they are equal, this means that the element is not present inside the list.
  • The function check_element() is called on different integer values.

Output

The following output displays how an element can be searched in a list in Python using the bisect functionalities:

Find Elements in a List in Python 4

Method 6: Find Elements in a Python List Using Counter() Function

Another method to find an element inside a list is using the counter() function that we can get from the collections module. It gets the frequency of each element inside the test list. The following code explains how to find an element inside a list using the counter() function from the collections module:

from collections import Counter
testlist = ['harry', 'taylor', 'lana']
def check_element(i):
    n = Counter(testlist)
    if(n[i] > 0):
        print(f"List has the required element {i}.")
    else:
        print(f"The list does not have the desired element {i}.")
check_element('lisa')
check_element('taylor')
check_element('harry')

In the above code, 

  • The counter function is imported from the collections module.
  • A test list is defined which contains string values of different names.
  • A function check_element is defined that takes an argument i. 
  • The variable n gets the frequency of elements in the test list.
  • An if-else statement is defined which checks if the frequency n[i]. If it is greater than 0 the list contains the element.
  • The check_element function is then checked for several string inputs.

Output

The output displays how to know if an element exists in a list in Python using the counter() function:

Find Elements in a List in Python 5

Method 7: Find Elements in a Python List Using count()

The count function in Python gets the frequency of each element inside the given “testlist”. Frequency having a value above 0 means the list has the required item. The following code explains how to find an element inside a list in Python using the count() function:

testlist = ['E', 'X', 'U']
def check_element(i):
    n=testlist.count(i)
    if n>0:
        print(f"List has the required element {i}.")
    else:
        print(f"The list does not have the desired element {i}.")
check_element('G')
check_element('F')
check_element('X')

In the above code,

  • A sample test list containing different letters is defined. A function check_element() is defined that takes an argument i.
  • The count() function gets the frequency of the element i and stores it in the variable n.
  • If the value of n is greater than 0, it means that the element is in the list otherwise it is not present in the list.
  • The check_element is called on different string inputs.

Output 

The following function displays how an element can be found in a list in Python using the count() function:

Find Elements in a List in Python 6

Method 8: Find Elements in a Python List Using try-except block and index()

The index() gets the index of an element inside the test list. The code is written inside a try-except block that throws a ValueError if the index() of an element does not exist. The code to find an element inside a Python list using the try-except block and the index() function is given as:

testlist = ['katherine', 'taylor', 'lisa']
def check_element(lst, i):
    try:
        ind = lst.index(i)
        print(f"The list has the required element {i} at the index position: {ind}")
    except ValueError:
        print(f"The list does not have the desired element {i}.")
check_element(testlist, 'katherine')
check_element(testlist, 'jade')
check_element(testlist, 'lisa')

In the above code,

  • A sample “testlist” is defined which contains different names as string inputs.
  • The function check_element is defined that takes two parameters list and i.
  • index() gets the index.
  • Inside the try-except block, if the index of an element is given, the message “The element is the list at index x” where x represents the index of an element is printed. In the other case, it will throw a ValueError that will print “The element is not in the list”.
  • The check_element is called on different inputs.

Output

The following output shows how an element inside a list can be found in Python using the try-except block and index() function:

Conclusion

Various methods in Python like any(), count(), find(), bisect module, or “in” statement can be used to search for an element in a list. Using the counter function from the collections module can be used to search an element by getting to know the frequency. Getting to know the element in the list is important for data modification and validation enabling streamlined programming operations. This article discusses different methods to find an element inside a Python list and illustrates each method with an example.