Find the index of Elements that meet a condition in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
6 min

banner

# Table of Contents

  1. Find the index of elements that meet a condition in Python
  2. Get index of the first List element that matches condition

# Find the index of elements that meet a condition in Python

To find the index of the elements that meet a condition:

  1. Use a list comprehension to iterate over a range object.
  2. Check if a condition is met and return the corresponding index if it is.
  3. The new list will only contain the indexes of the elements that meet the condition.
main.py
my_list = [4, 8, 12, 16, 25] indexes = [ index for index in range(len(my_list)) if my_list[index] > 10 ] print(indexes) # ๐Ÿ‘‰๏ธ [2, 3, 4]

find index of elements that meet condition

The code for this article is available on GitHub

We used a list comprehension to iterate over a range object containing the indexes in the list.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

The range() class is commonly used for looping a specific number of times.

main.py
my_list = [4, 8, 12, 16, 25] print(list(range(len(my_list)))) # ๐Ÿ‘‰๏ธ [0, 1, 2, 3, 4] print(list(range(5))) # ๐Ÿ‘‰๏ธ [0, 1, 2, 3, 4]

We used the list's length to construct a range object that contains all of the indexes in the list.

On each iteration, we check if the current list item is greater than 10 and return the result.

main.py
my_list = [4, 8, 12, 16, 25] indexes = [ index for index in range(len(my_list)) if my_list[index] > 10 ] print(indexes) # ๐Ÿ‘‰๏ธ [2, 3, 4]

The new list only contains the indexes of the elements that meet the condition.

You can use this approach to get the indexes of the elements that meet any condition in the list.

main.py
my_list = ['bobby', 'ab', 'cd', 'bobbyhadz.com'] indexes = [ index for index in range(len(my_list)) if my_list[index].startswith('bobby') ] print(indexes) # ๐Ÿ‘‰๏ธ [0, 3]

The example finds the indexes of the elements that start with a specific substring.

# Find the index of elements that meet a condition using NumPy

If you use NumPy, you can also use the numpy.where() method.

main.py
import numpy as np my_list = np.array([4, 8, 12, 16, 25]) indexes = np.where(my_list > 10)[0] print(indexes) # ๐Ÿ‘‰๏ธ [2 3 4] indexes = np.nonzero(my_list > 10)[0] print(indexes) # ๐Ÿ‘‰๏ธ [2 3 4]

find index of elements that meet a condition using numpy

The code for this article is available on GitHub

Make sure you have the NumPy module installed to be able to run the code sample.

shell
pip install numpy # ๐Ÿ‘‡๏ธ or pip3 pip3 install numpy

When only a condition is provided, the numpy.where() method returns the indices of the elements that meet the condition.

Alternatively, you can use a for loop.

# Find the index of elements that meet a condition using a for loop

This is a four-step process:

  1. Declare a new variable that stores an empty list.
  2. Use a for loop to iterate over the original list with enumerate().
  3. Check if a condition is met on each iteration.
  4. Append the matching indexes to the new list.
main.py
my_list = [4, 8, 12, 16, 25] indexes = [] for index, item in enumerate(my_list): if item > 10: indexes.append(index) print(indexes) # ๐Ÿ‘‰๏ธ [2, 3, 4]

find index of elements that meet condition using for loop

The code for this article is available on GitHub

We used the enumerate() function to get access to the index of the current iteration.

The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.

main.py
my_list = ['bobby', 'hadz', 'com'] for index, item in enumerate(my_list): print(index, item) # ๐Ÿ‘‰๏ธ 0 bobby, 1 hadz, 2 com

On each iteration, we check if the current element meets a condition.

If the condition is met, we use the list.append() method to append the current index to the new list.

The list.append() method adds an item to the end of the list.

main.py
my_list = ['bobby', 'hadz'] my_list.append('com') print(my_list) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz', 'com']

The method returns None as it mutates the original list.

# Get index of the first List element that matches condition

To get the index of the first list element that matches a condition:

  1. Use a generator expression to iterate over the list with enumerate().
  2. Check if each list item meets the condition and return the corresponding index.
  3. Pass the result to the next() function.
main.py
my_list = [2, 14, 29, 34, 72, 105] index_first_match = next( (index for index, item in enumerate(my_list) if item > 29), None ) print(index_first_match) # ๐Ÿ‘‰๏ธ 3 if index_first_match is not None: print(my_list[index_first_match]) # ๐Ÿ‘‰๏ธ 34
The code for this article is available on GitHub

We passed a generator expression to the next() function.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

We used the enumerate() function to get access to the index of the current iteration.

The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.

main.py
my_list = ['bobby', 'hadz', 'com'] for index, item in enumerate(my_list): print(index, item) # ๐Ÿ‘‰๏ธ 0 bobby, 1 hadz, 2 com

On each iteration, we check if the current list item is greater than 29 and if the condition is met, we return the current index.

The next() function returns the next item from the provided iterator.

The function can be passed a default value as the second argument.

If the iterator is exhausted or empty, the default value is returned.

If the iterator is exhausted or empty and no default value is provided, a StopIteration exception is raised.

We specified a default value of None but you can use any other value.

main.py
my_list = [2, 14, 29] index_first_match = next( (index for index, item in enumerate(my_list) if item > 29), None ) print(index_first_match) # ๐Ÿ‘‰๏ธ None if index_first_match is not None: print(my_list[index_first_match]) else: # ๐Ÿ‘‡๏ธ this runs print('No list element meets the condition')

None of the items in the list meets the condition, so the default value of None is returned.

Alternatively, you can use a for loop.

# Get index of the first List element that matches condition using for loop

This is a three-step process:

  1. Use a for loop to iterate over the list with enumerate().
  2. Check if each list item meets the condition.
  3. If the condition is met, assign the corresponding index to a variable.
main.py
my_list = [2, 14, 29, 34, 72, 105] index_first_match = None for index, item in enumerate(my_list): if item > 29: index_first_match = index break print(index_first_match) # ๐Ÿ‘‰๏ธ 3 if index_first_match is not None: # ๐Ÿ‘‡๏ธ this runs print(my_list[index_first_match]) # ๐Ÿ‘‰๏ธ 34 else: print('No list element meets the condition')

get index of first list element that matches condition using for loop

The code for this article is available on GitHub

We used a for loop to iterate over an enumerate object.

On each iteration, we check if the current list item meets a condition.

If the condition is met, we assign the current index to the index_first_match variable and exit the for loop.

The break statement breaks out of the innermost enclosing for or while loop.

There is no need to continue iterating once we've found a list item that meets the condition.

If no item in the list meets the condition, the index_first_match variable remains None.

If you need to find the indices of all list elements that meet the condition, store them in a list.

main.py
my_list = [4, 8, 14, 27, 35, 87] indices = [] for index, item in enumerate(my_list): if item > 8: indices.append(index) print(indices) # ๐Ÿ‘‰๏ธ [2, 3, 4, 5]

We removed the break statement and used the list.append() method to append the matching indices to the list.

The list.append() method adds an item to the end of the list.

main.py
my_list = ['bobby', 'hadz'] my_list.append('com') print(my_list) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz', 'com']

Which approach you pick is a matter of personal preference. I'd use the next() function because it's just as readable and a little more concise.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev