HomeLinuxPython Finds the Index of All Occurrences in a Listing

Python Finds the Index of All Occurrences in a Listing


Indexing” is a vital a part of working with lists in Python. It means that you can entry parts inside an inventory by their place. Generally, it could be mandatory to search out the index of all occurrences inside an inventory as per the requirement. On this article, we are going to discover 5 strategies to search out the index of all occurrences within the listing in Python, together with an instance code for every.

How you can Discover the Index of All Occurrences in a Listing?

To seek out the index of all occurrences in an inventory in Python, apply the next approaches:

Methodology 1: Discover the Index of All Occurrences in a Listing Using “for” Loop

The “for” loop is a basic management move assertion that means that you can run a chunk of code repeatedly. This loop can be utilized to iterate by means of the listing and discover the index of all occurrences of a specific factor.

Instance

Let’s take into account the next code snippet:

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

 

Within the above strains of code:

  • The “for” loop is used to iterate by means of the given listing and test if the iterated factor is the same as “55”.
  • When the worth is “55”, a brand new empty listing named “new_list” is appended with the corresponding indices.

Output

On this output, it may be seen that the index of all of the occurrences of particular listing merchandise has been displayed

Methodology 2: Discover the Index of All Occurrences in a Listing Utilizing the “enumerate()” Perform

The “enumerate()” perform is utilized to loop by means of an inventory and retailer an inventory of indexes and parts. This perform can be utilized within the under instance to search out the index of all occurrences of a specific factor as effectively.

Syntax

enumerate(iterable, begin=0)

 

Within the above syntax:

  • iterable” is any object that helps iteration.
  • begin” is the index worth from the place the counter begins. By default, it’s “0”.

Instance

Let’s overview the next code:

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

 

Within the above code:

  • The “enumerate()” perform is used within the “listing comprehension” to iterate by means of the actual listing and test for the index of the desired factor within the listing.
  • If the present factor of the given listing is the same as “55”, the index of that factor is appended to the brand new listing named “output”.

Output

Methodology 3: Discover the Index of All Occurrences in a Listing Utilizing the “index()” Methodology

The “index()” technique is utilized to retrieve the index of the primary occasion of a specified factor in an inventory. Though this technique solely finds the index of the primary incidence, we are able to use it together with a loop to search out the index of all occurrences.

Syntax

listing.index(worth, begin, finish)

 

Within the above-given syntax:

  • The “worth” parameter represents the actual worth to be looked for within the string or listing.
  • The parameter “begin” specifies the search’s beginning index. (Default is “0”)
  • The parameter “finish” signifies the ending index of the search. (Default worth is a string or listing size)

Instance

An inventory containing a specific factor might be listed by the next code:

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

 

In accordance with the above code block:

  • First, initialize the lists named “list_value” and “new_list”.
  • Within the “whereas” loop, the “index()” technique is used to search out the index of the primary incidence of “55” within the listing and appends it to the listing named “new_list”.
  • The “try-except” block is used to deal with the “ValueError” that’s raised when the “index()” technique can not discover any extra occurrences of “55”.

Output

This output exhibits the index of the primary occurrences of the precise worth within the listing.

Methodology 4: Discover the Index of All Occurrences in a Listing Utilizing the “defaultdict()” Perform

The “defaultdict()” perform is used to return a brand new dictionary-like object. This perform is used to make a dictionary the place the keys are the gadgets/parts of the listing and the values are the indices of all occurrences of that factor within the listing.

Syntax

defaultdict(default_factory)

 

Within the above syntax, the “default_factory” refers to a perform that returns the default worth for the lacking keys. The ”default_factory” might be “None”, a “lambda” perform, or an object that may be referred to as.

Instance

Let’s undergo the below-stated code:

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

 

Within the above code snippet:

  • Firstly, the “defaultdict()” perform is imported from the collections module.
  • After that, the listing named “list_value” is created.
  • The “defaultdict” object named “index_value” is initialized in this system. Which means that if a key will not be current within the “defaultdict” object, it’s going to return an empty listing by default.
  • The “enumerate()” perform is utilized to loop by means of the given listing and returns each the index and the worth of every factor.
  • The “for” loop is used to iterate by means of the listing by way of the “enumerate()” perform and appends the present index to the worth related to the present factor key within the indices dictionary.
  • Lastly, we print out the worth related to the important thing “55” within the indices dictionary.

Output

The above output shows the index of all occurrences of the actual worth in an inventory.

Conclusion

The “for” loop, “enumerate()” perform, “index()” technique, or the “defaultdict()” perform can be utilized to search out the index of all occurrences in an inventory in Python. These approaches apply the specified performance both by iterating by means of the listing or by dealing with the confronted exception. This put up offered numerous methods to search out the index of all occurrences in an inventory utilizing quite a few examples.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments