| by Arround The Web | No comments

Python Finds the Index of All Occurrences in a List

Indexing” is an essential part of working with lists in Python. It allows you to access elements within a list by their position. Sometimes, it may be necessary to find the index of all occurrences within a list as per the requirement. In this article, we will explore five methods to find the index of all occurrences in the list in Python, along with an example code for each.

How to Find the Index of All Occurrences in a List?

To find the index of all occurrences in a list in Python, apply the following approaches:

Method 1: Find the Index of All Occurrences in a List Utilizing “for” Loop

The “for” loop is a fundamental control flow statement that allows you to run a piece of code repeatedly. This loop can be used to iterate through the list and find the index of all occurrences of a particular element.

Example

Let’s consider the following code snippet:

list_value = [45, 55, 69, 55, 78, 55]
new_list = []
for i in range(len(list_value)):
    if list_value[i] == 55:
        new_list.append(i)
print(new_list)

 

In the above lines of code:

  • The “for” loop is used to iterate through the given list and check if the iterated element is equal to “55”.
  • When the value is “55”, a new empty list named “new_list” is appended with the corresponding indices.

Output

In this output, it can be seen that the index of all the occurrences of specific list item has been displayed

Method 2: Find the Index of All Occurrences in a List Using the “enumerate()” Function

The “enumerate()” function is utilized to loop through a list and store a list of indexes and elements. This function can be used in the below example to find the index of all occurrences of a particular element as well.

Syntax

enumerate(iterable, start=0)

 

In the above syntax:

  • iterable” is any object that supports iteration.
  • start” is the index value from where the counter starts. By default, it is “0”.

Example

Let’s overview the following code:

list_value = [45, 55, 69, 55, 78, 55]
output = [i for i, x in enumerate(list_value) if x == 55]
print(output)

 

In the above code:

  • The “enumerate()” function is used in the “list comprehension” to iterate through the particular list and check for the index of the specified element in the list.
  • If the current element of the given list is equal to “55”, the index of that element is appended to the new list named “output”.

Output

Method 3: Find the Index of All Occurrences in a List Using the “index()” Method

The “index()” method is utilized to retrieve the index of the first instance of a specified element in a list. Although this method only finds the index of the first occurrence, we can use it along with a loop to find the index of all occurrences.

Syntax

list.index(value, start, end)

 

In the above-given syntax:

  • The “value” parameter represents the particular value to be searched for in the string or list.
  • The parameter “start” specifies the search’s starting index. (Default is “0”)
  • The parameter “end” indicates the ending index of the search. (Default value is a string or list length)

Example

A list containing a particular element can be indexed by the following code:

list_value = [45, 55, 69, 55, 78, 55]
new_list = []
index_value = 0
while True:
    try:
        index_value = list_value.index(55, index_value)
        new_list.append(index_value)
        index_value += 1
    except ValueError:
        break
print(new_list)

 

According to the above code block:

  • First, initialize the lists named “list_value” and “new_list”.
  • In the “while” loop, the “index()” method is used to find the index of the first occurrence of “55” in the list and appends it to the list named “new_list”.
  • The “try-except” block is used to handle the “ValueError” that is raised when the “index()” method cannot find any more occurrences of “55”.

Output

This output shows the index of the first occurrences of the specific value in the list.

Method 4: Find the Index of All Occurrences in a List Using the “defaultdict()” Function

The “defaultdict()” function is used to return a new dictionary-like object. This function is used to make a dictionary where the keys are the items/elements of the list and the values are the indices of all occurrences of that element in the list.

Syntax

defaultdict(default_factory)

 

In the above syntax, the “default_factory” refers to a function that returns the default value for the missing keys. The ”default_factory” can be “None”, a “lambda” function, or an object that can be called.

Example

Let’s go through the below-stated code:

from collections import defaultdict
list_value = [45, 55, 69, 55, 78, 55]
index_value = defaultdict(list)
for i, x in enumerate(list_value):
    index_value[x].append(i)
print(index_value[55])

 

In the above code snippet:

  • Firstly, the “defaultdict()” function is imported from the collections module.
  • After that, the list named “list_value” is created.
  • The “defaultdict” object named “index_value” is initialized in the program. This means that if a key is not present in the “defaultdict” object, it will return an empty list by default.
  • The “enumerate()” function is utilized to loop through the given list and returns both the index and the value of each element.
  • The “for” loop is used to iterate through the list via the “enumerate()” function and appends the current index to the value associated with the current element key in the indices dictionary.
  • Finally, we print out the value associated with the key “55” in the indices dictionary.

Output

The above output displays the index of all occurrences of the particular value in a list.

Conclusion

The “for” loop, “enumerate()” function, “index()” method, or the “defaultdict()” function can be used to find the index of all occurrences in a list in Python. These approaches apply the desired functionality either by iterating through the list or by handling the faced exception. This post presented various ways to find the index of all occurrences in a list using numerous examples.

Share Button

Source: linuxhint.com

Leave a Reply