index of min element of sequence

Peter Otten __peter__ at web.de
Mon Jan 21 15:28:44 EST 2008


Roger Miller wrote:

> On Jan 21, 8:48 am, Peter Otten <__pete... at web.de> wrote:
> 
>> Neal Becker wrote:
>> > What's a good/fast way to find the index of the minimum element of a
>> > sequence?
> ...
> 
>> >>> min(xrange(len(items)), key=items.__getitem__)
> ...
> 
> Or just
>    items.index(min(items))
> I found this to be significantly faster in a simple test (searching a
> list of 1000 ints with the minimum in the middle), despite the fact
> that it requires two passes.  I'm sure that one could find cased where
> Peter's approach is faster, so you if you are concerned about speed
> you should measure with your own data.

I suppose those cases are rare (slow equality check), and even then I
might prefer your solution because it's so much clearer.

Peter



More information about the Python-list mailing list