Python Code Example: How To Find Element in a List in 6 Way

Do you want to learn how to find element in a list in 4 ways using Python? In this article, 4 different ways to check if the element exists in a List using Python.

Well, you check any elements in the list can be done really easily in Python using the “in” operator. Since the “in” operator returns true or false depending upon the presence of the element in the list. Let us see the details below with Examples.

1. Using in Operator to Find Element in a List

If you are given a list in Python then using the if condition and the in operator you can verify if the element is present in the list or not.

Let us see in the below example code the usage of if condition and in operator to find the element in a list using Python.

#Initializing a List with Some Data
givenList = [1,2,3,4,5,6]

#Initializing the key to find in List
key = 6

#Using in Operator Checking if key is present
#In the list
if key in givenList:
    print("{} is present in the list {}.".format(key, givenList))
else:
    print("{} is not found in the given List {}.".format(key, givenList))

Output:

6 is present in the list [1, 2, 3, 4, 5, 6].

As you can see in the above code, the key-value with 6 is present in the list provided, and hence using the “in” operator it successfully returned true when 6 was found in the list and allowed the first print statement to be executed.

Here the runtime complexity is linear i.e. O(n) where n is the number of elements in the list.

2. Using For Loop (Naive Approach) To Find Element in the List

You can find any element in the list by using the for loop and comparing the key element to each element of the list. Let us see in the below example code the usage of For loop to find an element in a list using Python.

#Initializing a List with Some Data
givenList = [1,2,3,4,5,6]

#Initializing the key to find in List
key = 3

#Intializing the bool to Mark the True or False
#If the Element is found
isFound = False

#Using For Loop To Check Elements
for element in givenList:
    if key == element:
        isFound = True
        break
if isFound:
    print("Element {} is found in the given List.".format(key))
else:
    print("Element {} is not found in the given List.".format(key))

Output:

Element 3 is found in the given List.

As you can see in the above code, I was able to search element 3 in the given list using the for a loop. But this naive approach makes the code a lot longer and does not offer any optimization, also the runtime complexity is linear i.e. O(n) for this code as well.

3. Using index Method From List Class To Check If Element is Present in List

You can use the index method present in the List Class of Python. This method searches for the index of the given element in the List and if the index is found then it returns the index value. If the element is not found then this method will throw a ValueError.

Let us see the usage of the Index Method in Python to check the index of the given element in the list.

#Initializing a List with Some Data
givenList = [1,2,3,4,5,6]

#Initializing the key to find in List
key = 10

#Using the index method to Search The Element
#Need to use Try Catch for Element not found
try:
    getIndex = givenList.index(key)
    print("The element {} is Found in the {} List.".format(key, givenList))
except ValueError:
    print("The Given Element is Not Found.")

Output:

The Given Element is Not Found.

As you can see in the above code, the given key 10 is not present in the given list hence the ValueError is thrown by Python that is caught using except, and then I have printed that element is not present in the list.

Note that the runtime complexity for the above code remains the same as Linear i.e. O(n).

4. Using filter Method in Python To Find Element in List

You can use the filter method to search if the element is present in the list or not. This method returns all the occurrences of the elements in the given list. Let us see in the below example code the usage of the filter method in Python.

#Initializing a List with Some Data
givenList = [1,2,3,4,5,6]


#Using Filter Method to search for the Element
#In The List
isFound = [elem for elem in givenList if elem==6]

if len(isFound) != 0:
    print("Element is found in the list.")
else:
    print("Element is not found.")

Output:

Element is found in the list.

As you can see in the above code element 6 is present in the list and hence the isFound list contains element 6 that sets the if condition as True and hence it prints the element is found in the list.

5. Using Next Method To Check First Occurrence of Element in The List

If you only want to search if the element is present in the list irrespective of the number of times it is present and want to end the search immediately to optimize the search then you need to use the Next[1] Method in Python.

Let us see in the below example code the usage of the next method in Python to search the Element in List.

#Initializing a List with Some Data
givenList = [1,2,3,4,5,6]


#Using Next Method to search for the Element
#In The List
isFound = next(elem for elem in givenList if elem==1)

if isFound != 0:
    print("Element is found in the list.")
else:
    print("Element is not found.")

Output:

Element is found in the list.

This method returns 1 if the element is present in the list and once the first occurrence is found it comes out of the function. Otherwise, it keeps searching till the end of the list and returns 0 if not found.

6. Using Count Method in Python To Seach for Element in The List

You can also use the count method to check if the element is present in the list or not. This method counts all the occurrences of the input value in the given list and returns the number of occurrences found.

Let us see in the below code usage of the count method to search elements in the given list using Python.

#Initializing a List with Some Data
givenList = [1,2,3,4,5,6]

#Initializing Key
key = 10

#Using Count Method to search for the Element
#In The List
numOfOccurence = givenList.count(key)

if numOfOccurence:
    print("Element {} is found in the list.".format(key))
else:
    print("Element {} is not found.".format(key))

Output:

Element 10 is not found.

As you can see the number 10 is not present in the list and hence the count function counts a total number of occurrences of 10 in the given list as 10 and hence the element is not found in the list. This method is not very efficient to use.

Python Code Example: How To Find Element in a List in 6 Way

Wrap Up

I hope you were able to get the answer to the problem of how to find an element in List In Python. I have listed down a total of 6 methods for you that you can use to find the element in the list easily.

Let me know in the comment section if you know any better method than the one discussed here I will be happy to add it here.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. How To Iterate Over Rows in a DataFrame in Pandas Python
  2. Python Get Filename From A Path Without Extension 4 Ways
  3. How To Concatenate String and Integer In Python
  4. Code Example: Convert a String to DateTime in Python
  5. How Do I Sort A Dictionary By Value In Python
  6. Code Example: How To Add Numbers In A List Python
  7. Python – How To Delete All Files In A Directory

Leave a Comment