Returning the positions of a list that are non-zero

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Jul 9 01:55:06 EDT 2008


Benjamin Goudey <bwgoudey at gmail.com> writes:

> 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.

The built-in 'enumerate' function is made for this. Creating the new
list can be done efficiently and clearly with a list comprehension.
Further, presumably you want to do further operations on these new
series of data; wouldn't it be better to have the values and original
indices actually correlated together?

This code produces a two-element tuple for each original non-zero
value:

    >>> sparse_data = [0, 0, 1, 2, 1, 0, 0]
    >>> nonzero_data = [(index, value)
    ...     for (index, value) in enumerate(sparse_data)
    ...     if value != 0]
    >>> nonzero_data
    [(2, 1), (3, 2), (4, 1)]
    >>> for (index, value) in nonzero_data:
    ...     print "Value %(value)r was originally at index %(index)r" % vars()
    ...
    Value 1 was originally at index 2
    Value 2 was originally at index 3
    Value 1 was originally at index 4

-- 
 \             “Experience is that marvelous thing that enables you to |
  `\   recognize a mistake when you make it again.” —Franklin P. Jones |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list