Last updated: Apr 10, 2024
Reading timeยท6 min
To find the index of the elements that meet a condition:
range
object.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.
The range() class is commonly used for looping a specific number of times.
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.
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.
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.
If you use NumPy, you can also use the numpy.where()
method.
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.
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.
This is a four-step process:
for
loop to iterate over the original list with enumerate()
.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.
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.
my_list = ['bobby', 'hadz'] my_list.append('com') print(my_list) # ๐๏ธ ['bobby', 'hadz', 'com']
The method returns None as it mutates the original list.
To get the index of the first list element that matches a condition:
enumerate()
.next()
function.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.
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.
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.
StopIteration
exception is raised.We specified a default value of None
but you can use any other value.
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.
This is a three-step process:
for
loop to iterate over the list with enumerate()
.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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: