Python Find in List: How to Find an Element in List

Python list is an actual container as it stores elements of all the data types as a collection. Therefore, knowledge of certain list operations is necessary for day-day programming.

Why is it useful to be able to find elements in a list

Finding elements in a list is helpful because it lets you do things or get information based on the presence or absence of certain items in the list.

To avoid creating duplicate elements in the list, you must check if an element is already in a list before adding it. Or, you may want to find the index of an element in a list to use it to access other elements or slice the list.

Counting the number of elements in a list can also help with statistical analysis or data processing.

Finding substrings in a list of strings can also help process text or matching patterns.

How to Find an element in the list in Python

6 easy ways to check if an element is in the list in Python.

  1. Using the “index()” method to find the index of an element in the list.
  2. Using the “in operator” to check if an element is in the list.
  3. Using the “count()” method to count the number of occurrences of an element in the list.
  4. Using the “any()” function.
  5. The “filter()” function creates a new list of elements based on conditions.
  6. Using the “for loop”.

Technique 1: Using the “index()” method

To find an element in the Python list, use the list index() method.

The list index() is a built-in method that searches for an element in the list and returns its index.

If the same element is present more than once, the method returns the index of the first occurrence of the element.

The index in Python starts from 0, not 1. So, through an index, we can find the position of an element in the list.

# app.py

streaming = ['netflix', 'hulu', 'disney+', 'appletv+']

index = streaming.index('disney+')
print('The index of disney+ is:', index)

Output

➜  pyt python3 app.py
The index of disney+ is: 2
➜  pyt

The list.index() method takes a single argument, the element, and returns its position in the list.

Technique 2: Using “in operator”

Use the “in operator” to check if an element is in the list.

main_list = [11, 21, 19, 46]

if 19 in main_list:
    print("Element is in the list")
else:
    print("Element is not in the list")

Output

Element is in the list

You can see that the element “19” is in the list. That’s why “in operator” returns True.

If you check for the element “50,” then the “in operator” returns False and executes the else statement.

Technique 3: Using the count() function

The list.count() method returns the number of times the given element in the list.

Syntax

list.count(element)

The count() method takes a single argument element, the item that will be counted.

Example

main_list = [11, 21, 19, 46]

count = main_list.count(21)

if count > 0:
    print("Element is in the list")
else:
    print("Element is not in the list")

Output

Element is in the list

We count the element “21” using the list in this example.count() function, and if it is greater than 0, it means the element exists; otherwise, it is not.

Technique 4: Using list comprehension with any()

The any() is a built-in Python function that returns True if any item in an iterable is True. Otherwise, it returns False.

main_list = [11, 21, 19, 46]

output = any(item in main_list for item in main_list if item == 22)

print(str(bool(output)))

Output

False

You can see that the list does not contain “22”. So, finding “22” in the list will return False by any() function.

If any() function returns True, then an element exists in the list; otherwise, it does not.

Technique 5: Using the filter() method

The filter() method iterates through the list’s elements, applying the function to each.

The filter() function returns an iterator that iterates through the elements when the function returns True.

main_list = [11, 21, 19, 46]

filtered = filter(lambda element: element == 19, main_list)

print(list(filtered))

Output

[19]

In this example, we use the filter() function that accepts a function and lists it as an argument.

We used the lambda function that will check if the input element is the same as any element from the list, and if it does, it will return an iterator.

To convert an iterator to a list in Python, use the list() function.

We used the list() function to convert an iterator returned from the filter() function to the list.

Technique 6: Using the for loop

You can find if an element is in the list using the for loop in Python.

main_list = [11, 21, 19, 46]

for i in main_list:
    if(i == 46):
        print("Element Exists")

Output

Element Exists

In this example, we traversed a list element by element using the for loop, and if the list’s element is the same as the input element, it will print “Element exists”; otherwise not.

Python search on the list

It is a straightforward approach to doing a linear search. For example,

  1. Start from the leftmost item of the list, and compare x with each item one by one.
  2. If x matches with an item, return True.
  3. If x doesn’t match with any of the items, return False.
# app.py

def search(list, platform):
    for i in range(len(list)):
        if list[i] == platform:
            return True
    return False


streaming = ['netflix', 'hulu', 'disney+', 'appletv+']
platform = 'netflix'

if search(streaming, platform):
    print("Platform is found")
else:
    print("Platform does not found")

We have first created a user-defined function called a search that accepts two arguments in the above code.

The first argument is our list, where we need to find the item, and the second parameter is the platform, which is the string we need to search in the list.

So, we are looping through a list and comparing each list element to the platform argument.

If both are matched, the element is found; otherwise, it is not.

Output

➜  pyt python3 app.py
Platform is found
➜  pyt

Potential errors while finding an element in the list

IndexError: list index out of range

The IndexError: list index out of range error occurs when you try to access an index that is out of range of the list.

main_list = [11, 21, 19, 46]

print(main_list[6])

Output

IndexError: list index out of range

Fixing the error

To prevent the IndexError, you can check the index is not out of range before trying to access it.

main_list = [11, 21, 19, 46]

# Checking the index before accessing
if 6 < len(main_list):
  print(main_list[6])
else:
  print("Index is out of range")

Output

index is out of range

You can see that we used the if-else condition to check if the index is out of range, and if it does, then we are simply printing the statement quoting “index is out of range”.

ValueError: ‘element’ is not in list

The ValueError: ‘element’ is not in list error occurs when attempting to find an element in a list that does not exist in the list.

main_list = [11, 21, 19, 46]

print(main_list.index(6))

Output

ValueError: 6 is not in list

You can see that element “6” is not on the list.

Fixing the error

Before finding its index, you must check if the value is in the list.

main_list = [11, 21, 19, 46]

if 6 in main_list:
  print(main_list.index(6))
else:
  print("Element does not exist in the list")

Output

Element does not exist in the list

We avoided the ValueError by checking if an element exists in the list using the “in operator”.

NameError: name ‘k’ is not defined

The NameError: name ‘k’ is not defined error occurs when you try to find an element in a list using a variable that is not defined.

main_list = [11, 21, 19, 46]

print(main_list.index(k))

Output

NameError: name 'x' is not defined

Fixing the error

To prevent the NameError, you can define the variable before using it.

main_list = [11, 21, 19, 46]
k = 19
print(main_list.index(k))

Output

2

You can see that after defining “k = 19”, we got the index of the element “19”, which is 2, and we get that in the output. And it resolved the error as well.

FAQ

How do I check if an item exists in a list in Python?

Use the “in operator” to check if an element exists in a list.

Can I use the find() method to check if an item exists in a list?

Python does not have a built-in find() method on the list object, but you can use the index() method to check if an item exists in a list.

How to find the index of an element in a list in Python?

You can find the index of an element in a list using the index() method.

How to find the first occurrence of an item in a list in Python?

Use the index() method to find the first occurrence of an element in a list.

How to find the unique elements in a list in Python?

You can use the set() function to create a set of unique elements from a list.

Conclusion

Python list contains different data types like integer, string, boolean, etc. Sometimes, it requires searching for particular elements in the list.

The elements can be searched in the Python list in various ways. We have seen the ways to search elements in the list by index and linear search on the list.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.