# Returning the positions of a list that are non-zero

Luis Zarrabeitia kyrie at uh.cu
Wed Jul 9 12:06:44 CEST 2008

```This could work:

l = [0,0,1,2,1,0,0]
indexes, values = zip(*((index,value) for index,value in enumerate(l) if value
!= 0))

But I guess it would be a little less cryptic (and maybe a lot more efficient)
if there were an unzip function instead of using the zip(*sequence) trick.

I think a more readable way would be:

indexes = [index for index,value in enumerate(l) if value != 0]
values = [value for value in l if value != 0]

Cheers.

--
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie

Quoting Benjamin Goudey <bwgoudey at gmail.com>:

> I have a very large list of integers representing data needed for a
> histogram that I'm going to plot using pylab. However, most of these
> values (85%-95%) are zero and I would like to remove them to reduce
> the amount of memory I'm using and save time when it comes to plotting
> the data. To do this, I'm trying to find the best way to remove all of
> the zero values and produce a list of indices of where the non-zero
> values used to be.
>
> For example, if my original list is [0,0,1,2,1,0,0] I would like to
> produce the lists [1,2,1] (the non zero values) and [2,3,4] (indices
> of where the non-zero values used to be). Removing non-zero values is
> very easy but determining the indicies is where I'm having difficulty.
>
> Thanks in advance for any help
> --
> http://mail.python.org/mailman/listinfo/python-list
>

```