Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a list of indices of non zero elements in a list?

I have a list that will always contain only ones and zeroes. I need to get a list of the non-zero indices of the list:

a = [0, 1, 0, 1, 0, 0, 0, 0] b = [] for i in range(len(a)):     if a[i] == 1:  b.append(i) print b 

What would be the 'pythonic' way of achieving this ?

like image 631
George Profenza Avatar asked Nov 06 '10 01:11

George Profenza


People also ask

How do you find non-zero elements in a list Python?

nonzero() function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values in the array can be obtained with arr[nonzero(arr)] .

How do you find the list of indices?

The list index() method helps you to find the index of the given element. This is the easiest and straightforward way to get the index. The list index() method returns the index of the given element.

How do you get the indices of all occurrences of an element in a list in Python?

One of the most basic ways to get the index positions of all occurrences of an element in a Python list is by using a for loop and the Python enumerate function. The enumerate function is used to iterate over an object and returns both the index and element.

How do I find the first non-zero value of a list in Python?

Use the nonzero() Function to Find the First Index of an Element in a NumPy Array. The nonzero() function returns the indices of all the non-zero elements in a numpy array. It returns tuples of multiple arrays for a multi-dimensional array.


2 Answers

[i for i, e in enumerate(a) if e != 0] 
like image 128
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 05:09

Ignacio Vazquez-Abrams


Not really a "new" answer but numpy has this built in as well.

import numpy as np a = [0, 1, 0, 1, 0, 0, 0, 0] nonzeroind = np.nonzero(a)[0] # the return is a little funny so I use the [0] print nonzeroind [1 3] 
like image 41
Brian Larsen Avatar answered Sep 28 '22 03:09

Brian Larsen