Find Items & Indices In A List...

Bengt Richter bokr at oz.net
Fri Dec 10 20:54:11 CET 2004


On Fri, 10 Dec 2004 16:27:29 GMT, Steven Bethard <steven.bethard at gmail.com> wrote:

>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...
>
>Everyone has already given you the answer (enumerate in a LC or GE), I'd 
>just comment that it's easy enough to extend their answers to any given 
>condition:
>
> >>> def getindices(sequence, predicate):
>... 	return [i for i, v in enumerate(sequence) if predicate(v)]
>...
> >>> getindices([0,1,1,1,1,5,6,7,8,1,10], bool)
>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> >>> def equalsone(v):
>... 	return v == 1
>...
> >>> getindices([0,1,1,1,1,5,6,7,8,1,10], equalsone)
>[1, 2, 3, 4, 9]
> >>> def f(v):
>... 	return pow(v, 3, 4) == 3
>...
> >>> getindices([0,1,1,1,1,5,6,7,8,1,10], f)
>[7]
>
Conclusion:
Python is programmer's Lego ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list