How to find index of all occurrences in list in Python

List is a data type in Python. It is used to store multiple values in one variable. If you want to find out how many times a certain element shows up in a list and where – you’ve come to the right place.

In this tutorial, we’ll show you how to find index of all occurrences in list in Python. Let’s get started.
Imagine we have a python list –

Let’s count the occurrences for this list. We’ll be showing you seven methods that you can use. They are –

The easiest method – Using list count() method

The count() method will return the occurrences of any element in a list. Let’s find out how many times 4 occurs in our list with this method. Here’s the code –

3

This is the easiest method to count the occurrences. However, this method does not provide the indices of the specified element.
The following methods will show you the count as well as the indices of where those specific elements are.

The Basic Method – Using for loops

You can just write a for loop that will find out the occurrences for a specified element in a list. Let’s take a look at the following code –

[3, 7, 8] 3

In this piece of code, we defined a function that takes a list and the element as input and returns the indices of that specific element. The for loop inside the function checks each of the items in the list and registers the indices where the specified item/element is. After that, we can just find the number of occurrences using the len() function like in the code.

The shortest method – Using the enumerate() function

The enumerate() function in python adds an index number to any iterable and returns an object. Let’s see it in action by looking at the object which enumerate() function returns –

[(0, 1), (1, 2), (2, 3), (3, 4), (4, 10), (5, 12), (6, 6), (7, 4), (8, 4), (9, 2), (10, 0)]

As you can see, we converted the enumerate object into a list and printed it. The output is in the format of (index, element). This is how the enumerate() function added an index to each element of the original list.
Now we’ll show you a one-line code to find out the occurrences. We’ll use list comprehension with the enumerate() function –

[3, 7, 8] 3

Here, enumerate(onelist) returned pairs (index, element) and we looped through all of those pairs, filtered the element of our interest, and stored the indices of those elements.

The fastest method – Using a numpy array

For this method, you will need the numpy library. Numpy arrays are better than lists mainly because of the following reasons –

  • Numpy arrays only contain a single data type while the lists may contain different data types. This makes the numpy arrays smaller in size and more optimized than the lists.
  • Numpy arrays are faster than lists.
  • Numpy arrays have much better and more optimized functionality than lists.
    Now that you know why Numpy arrays are better, let’s dive into the program using the numpy array –
    [3, 7, 8] 3

    In this piece of code, we imported the numpy library at first. Then we converted our list into a numpy array. The numpy where() method returns the indices when some certain condition is met. In our case, we set the condition to be equal to 4 and got the indices of 4 in the array. After that, we just simply print out the indices and the number of occurrences with the len() function.

    Using itertools module

    The itertools library includes some efficient iterators. The count() function is an infinite iterator. We used the zip() function to join two lists together. Let’s see the code in action –

    [3, 7, 8] 3

    In the code, we iterate through the list, and the zip() function stitches each element and their indices that count() outputs. We set the zipper variable to only include the indices of the element of our interest using the if statement.

    Using more-itertools Library

    We can also use the locate() function in the more-itertools library. The locate() function returns the indices of an iterable where some conditions are met. Keep in mind, you will require the more_itertools library before you can run this code. Let’s jump into the code –

    [3, 7, 8] 3

    Here, the locate() function iterates through the list and stores the indices when it encounters element 4.

    Using index() function

    In this method, we’ll use the index() function. The index() function outputs the lowest index of an element. However, we can code to get the indices of all the occurrences. Here is the code –

    [3, 7, 8] 3

    The index function takes in inputs of where to start the countdown from. The syntax is listname.index(element, start, end). In the above piece of code, we increased the start value for the index() function and got the output of the indices of 4.

    That’s all about find index of all occurrences in list in Python.

Related Posts

  • 07 January

    How to compare lists in Python

    Table of ContentsPython compare listsHow to compare lists in PythonUsing the sort() function and == operatorUsing the map() and reduce() functionsUsing the set() function and == operatorUsing the for loopUsing the set() function and - operatorUsing the collections.Counter() class and == operatorUsing the zip(), sum(), and len() functionsUsing the cmp() functionConclusion In this post, we […]

  • Python List of dictionaries
    09 December

    List of Dictionaries in Python

    Table of ContentsHow to Create a List of Dictionaries in Python?How to Access Elements of a List of Dictionaries?Search in a List of Dictionaries in PythonUpdate Values in a List of Dictionaries in PythonHow to Sort List of Dictionaries in Python?Conclusion We use both lists and dictionaries in our python programs. Lists are used to […]

  • Python sort list of lists
    17 November

    Sort List of Lists in Python

    Table of ContentsSort List of Lists Using the sort() Method in PythonUsing the itemgetter() methodUsing Lambda FunctionsSort List of Lists Using the sorted() Function in PythonSort lists of lists on the basis of the length of the inner listsConclusion Several times we use 2-D lists or lists of lists in our programs to represent a […]

  • Remove nan from list in Python
    16 November

    Remove nan From List In Python?

    Table of ContentsWhat is nan in python?How to remove nan from list in python?Remove nan from list using the str() functionRemove nan from list using math.isnan() functionRemove nan from list using numPy.isnan() functionRemove nan from list using pandas.isnull() functionConclusion In python, nan is a special value used to represent missing values. In this article, we […]

  • List intersection in Python
    11 November

    List intersection in python

    Table of ContentsWhat is the list intersection in Python?Ways to find the list intersection in PythonUsing the for loop to achieve list intersection in PythonUsing the set() function to find list intersection in PythonUsing the intersection() function to find list intersection in PythonUsing the filter() and lambda functions to find list intersection in PythonUsing the […]

  • Initialize list with zeros in Python
    25 October

    Four Ways To Initialize List With Zeros In Python

    Table of ContentsWhy Initialize List with Zeros in Python?How Can We Initialize List With Zeros In Python?Initialize List With Zeros Using * Operator In PythonInitialize List With Zeros Using  itertools.repeat() FunctionInitialize List With Zeros Using  Generator Comprehension In PythonInitialize List With Zeros Using  List Comprehension In PythonConclusion Lists in Python are one of the most […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.