Get the indices of all occurrences of an element in a Python list

Given a list x and an element target, the goal is to find all the occurrences of the target element in the list. For example, for the given input:

getIndices([1,2,3,4,1,5,1], 1)

The output should be as follows:

[0, 4, 6]

Naive solution

Let's try to implement a naive solution first:

def getIndices(x, target):
# list to store indices
indices = []
# loop to iterate over the list elements
for i in range(len(x)):
# if the element matches the target element, store its index
if x[i] == target:
indices.append(i)
# return indices
return indices
print(getIndices([1,2,3,4,1,5,1], 1))

Explanation

  • Line 1: We define our function, which takes two parameters: a list x and a target element target.

  • Line 3: We create a list to store the indices of the target element.

  • Lines 5–8: We iterate over the list of elements and check if an element matches the target element. If yes, we store the index of that element in the indices list.

  • Line 11: We return the indices list.

Optimized solution

Our naive solution has a time complexity of O(n), which isn't bad. However, we can optimize the performance by using list comprehension, which is generally faster than using a for loop.

The following image demonstrates list comprehension.

List comprehension
List comprehension

Here is the complete code:

def getIndices2(x, target):
indices = [i for i in range(len(x)) if x[i]==target]
return indices
print(getIndices2([1,2,3,4,1,5,1], 1))

Explanation

  • Line 1: We define our function as before.

  • Line 2: We use list comprehension and get the indices of the elements in the list x that match the target element.

  • Line 4: We return the indices list.

Our optimized solution still has the time complexity of O(n); however, list comprehension may offer faster execution time, especially for larger lists.

Note: While list comprehension has its performance benefits, using it with multiple if conditions can make our code harder to read and debug. In that case, using a for loop might be a better option.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved