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


To retrieve the indices of all occurrences of a specific element in a list using Python we can use methods like using for loop, using list comprehension, using enumerate() function, using the index() method in a while loop, etc. In this article, we will explore these different methods and perform the operations to get the indices of all occurrences of an element in a list.

Method 1: Using for loop

In this method, we start iterating through the list and comparing each element to the desired element. If the element matches we add its index to the index list.

Algorithm

  • Initialize an empty list called indices to store the indices of occurrences.

  • Iterate through the list using a for loop and the range() function.

  • Check if the current element at index i is equal to the desired element.

  • If it is, append the index i to the indices list.

  • Return the indices list.

Syntax

for i in range(len(lst)):
        if lst[i] == element:
            indices.append(i)

Here, in the for loop the variable i iterates over the length of the list and compares each element of the list with the required element. indices.append(i) , appends the index to the indices list if the element matches.

Example

In the below example, we find and print the indices of all occurrences of the element '3' in the list 'my_list'. The 'get_indices()' function is called with the element and the list as arguments, which returns a list of indices. This list is then printed using the 'print()' function.

def get_indices(element, lst):
    indices = []
    for i in range(len(lst)):
        if lst[i] == element:
            indices.append(i)
    return indices
my_list = [3, 5, 2, 3, 8, 3, 1]
element = 3
indices = get_indices(element, my_list)
print(indices)

Output

[0, 3, 5]

Method 2: Using list comprehension

This method allows us to create a new list that contains the indices of all occurrences of the desired element.

Algorithm

  • Use list comprehension to generate a new list of indices.

  • Iterate through the list using the range() function.

  • Include the index i in the new list if the element at that index matches the desired element.

  • Return the new list.

Syntax

[i for i in range(len(lst)) if lst[i] == element]

Here, the list comprehension checks for each element in the list and compares it with the required element. If it matches we can print the indices.

Example

def get_indices(element, lst):
    return [i for i in range(len(lst)) if lst[i] == element]


my_list = [3, 5, 2, 3, 8, 3, 1]
element = 3
indices = get_indices(element, my_list)
print(indices)

Output

[0, 3, 5]

Method 3: Using the enumerate() function

The enumerate() function is a useful tool in Python that simplifies iterating over a list while keeping track of the index and the corresponding element. This method allows us to directly obtain the indices of all occurrences of the desired element.

Algorithm

  • Utilize list comprehension to create a new list of indices.

  • Iterate over the list using the enumerate() function, which provides both the index i and the element x.

  • Include the index i in the new list if the element x matches the desired element.

  • Return the new list

Syntax

def get_indices(element, lst):
    return [i for i, x in enumerate(lst) if x == element]

Here, [i for i, x in enumerate(lst) if x == element] is used to iterate over the list lst using enumerate() to obtain both the index and the element, and filters only the indices where the element matches the desired element.

Example

In the below example, we define a function get_indices() that takes an element and a lst as arguments. It uses list comprehension to iterate over the enumerated list lst and checks if each element x is equal to the given element. It returns a list of indices for which this condition is true. In the provided example, the function is called with element = 3 and my_list = [3, 5, 2, 3, 8, 3, 1], resulting in the output [0, 3, 5], which are the indices of all occurrences of the element 3 in the list.

def get_indices(element, lst):
    return [i for i, x in enumerate(lst) if x == element]

my_list = [3, 5, 2, 3, 8, 3, 1]
element = 3
indices = get_indices(element, my_list)
print(indices)

Output

[0, 3, 5]

Method 4: Using the index() method in a while loop

Another approach to finding the indices of all occurrences of an element is by using the index() method in combination with a while loop. This method help us to locate and record the indices incrementally.

Algorithm

  • Initialize an empty list called indices to store the indices of occurrences.

  • Initialize a variable index with a value of −1.

  • Enter a while loop that continues until a ValueError is raised.

  • Inside the loop, attempt to find the next occurrence of the desired element using the index() method.

  • If a match is found, append the index to the indices list and update the index variable to continue searching from the next position.

  • If no match is found, a ValueError is raised, and the loop breaks.

  • Return the indices list

Syntax

index = lst.index(element, index + 1)

Here, index() method searches for the first occurrence of the given element starting from the index index + 1. It assigns the found index to the variable index. This allows us to locate subsequent occurrences of the element by incrementing the index and searching again

Example

def get_indices(element, lst):
    indices = []
    index = -1
    while True:
        try:
            index = lst.index(element, index + 1)
            indices.append(index)
        except ValueError:
            break
    return indices

my_list = [3, 5, 2, 3, 8, 3, 1]
element = 3
indices = get_indices(element, my_list)
print(indices)

Output

[0, 3, 5]

Conclusion

In this article, we discussed how we can get the indices of all occurrences of an element in a list using different methods in Python.We explored four different methods to implement this task: using a for loop, list comprehension, the enumerate() function, and the index() method with a while loop. Each method has its own advantages, and the choice depends on personal preference and the specific requirements of the problem at hand.

Updated on: 18-Jul-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements