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

Last updated: Apr 10, 2024
6 min

## #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
```Copied!```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]
``````

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
```Copied!```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
```Copied!```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
```Copied!```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
```Copied!```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]
``````

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

shell
```Copied!```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
```Copied!```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]
``````

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
```Copied!```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
```Copied!```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
```Copied!```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
``````

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
```Copied!```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
```Copied!```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
```Copied!```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')
``````

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
```Copied!```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
```Copied!```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.