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
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
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)) )
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
The trick is quite general and so it should generalize to languages with similar functionality on tuples and lists.