Find indices of the non-zero elements in the Python list

In this tutorial, we are going to see how to find indices of the non-zero elements in the Python list. There may be instances when we need to access only the non-zero elements in the list. We can use the following methods in such cases.

Naive and Simple method

Well, if we want to find the index of non-zero elements of a list, we can use a for loop to iterate the list and store the index values in a different list. We have done this implementation in the following program. Have a look at the code.

li = [2, 0, 5, 7, 0, 9]
li_new = []
for i in range(len(li)):
    if li[i]!=0:
        li_new.append(i)
print(li_new)

Output:

[0, 2, 3, 5]

As it’s clear from the output, the list has non-zero values at indexes 0, 2, 3 and 5.

Using enumerate() and list comprehension

Another way to find the indices of the non-zero elements is the method followed in the given example program. This is a shorthand implementation of the above algorithm. In this method, we are using the enumerate() method to convert the list into iterable. If you don’t know about the enumerate() method, do give it a read: Enumerate() Method in Python

We are also using list comprehension to keep it short. See the code for a better understanding.

li = [2, 0, 5, 7, 0, 9]

li_new = [i for i, element in enumerate(li) if element!=0]

print(li_new)

Output:

[0, 2, 3, 5]

As you can see, the program returns indices for the non-zero elements.

Using NumPy.array

We can also access non-zero elements of a list using numpy. First, we import this module. Then we convert the given list into a numpy array as shown below. NumPy provides us with a nonzero() method which returns a tuple of arrays containing indices of the nonzero elements. We can again typecast it to a list and print the new list. Have a look at the following program. This explains the algorithm.

import numpy as np

li = [2, 0, 5, 7, 0, 9]
arr = np.array(li)
li_new = list(np.nonzero(arr)[0]) 

print(li_new)

Output:

[0, 2, 3, 5]

Hope it helped. Thank you.

Also read: Take multiple inputs in a single line: Python?

Leave a Reply