Last Updated: February 25, 2016
·
15.86K
· 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!

308.8K
7

271.7K
23

### Emulate do-while loop in Python

246.5K
2

#### 2 Responses 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 ·

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 ·

#### Have a fresh tip? Share with Coderwall community!

Best #Python Authors terrasea
308.8K cheglastgnat
271.7K  saji89
246.5K lotia
187.1K
Awesome Job