a9hvrg
Last Updated: February 25, 2016
·
3.767K
· antonov

Index of minimum element of a list

Computing the minimum element of a list is a very common task in programming. In Python, one computes the minimum of a list with the built-in function min.

Now, what if, in addition to the value of a minimum element, we also need to compute an index of such an element in the list? How can we do that without writing explicit loops, in one line, using the same min function?

Here's a one-liner providing both the value of the minimum as well as the first index where it is realized:

>>> l = [33, 788, 1, -14, 78, 11, 32, 11, 78, -1, -14]
>>> mn,idx = min( (l[i],i) for i in xrange(len(l)) )
>>> mn,idx
(-14, 3)

The reason why this works is because the default order of tuples in Python is lexicographical, with most significant component on the left.

Needless to say, the tip also applies to computing the maximum element, with the built-in max function.

The trick is quite general and so it should generalize to languages with similar functionality on tuples and lists.

Enjoy!

Say Thanks
Respond

2 Responses
Add your response

6627
Mypic

very cool. Can you explain a bit more about what it means that "the default order of tuples in Python is lexicographical" ?

over 1 year ago ·
6628

Sure. It means that, by default, Python considers that tuple (a,b) is less than or equal than (a',b') if and only if a is less than a' or if a equals a' and b is less than or equal than b'.

In symbols: (a,b) <= (a',b') if and only if a < a' or ( a == a' and b <= b' ).

I'll link the term 'lexicographical order' to the Wikipedia article in my protip. Thanks!

over 1 year ago ·