Find Items & Indices In A List...
Ola Natvig
ola.natvig at infosense.no
Fri Dec 10 10:24:03 EST 2004
andrea.gavana at agip.it wrote:
> Hello NG,
>
> I was wondering if there is a faster/nicer method (than a for loop)
> that will allow me to find the elements (AND their indices) in a list that
> verify a certain condition. For example, assuming that I have a list like:
>
> mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1, 10]
>
> I would like to find the indices of the elements in the list that are equal
> to 1 (in this case, the 1,2,3,4,9 elements are equal to 1). I could easily
> use a for loop but I was wondering if there is a faster method...
>
> Thanks for every suggestion.
>
> Andrea.
> ------------------------------------------------------------------------------------------------------------------------------------------
> Message for the recipient only, if received in error, please notify the
> sender and read http://www.eni.it/disclaimer/
>
>
You could do a list comprehension /generator expression. Like this:
[i for i in range(len(mylist)) if mylist[i] == 1]
--
--------------------------------------
Ola Natvig <ola.natvig at infosense.no>
infoSense AS / development
More information about the Python-list
mailing list