This is similar to @Jon Clements's answer. His uses heapq
which means it can be used to find more than one smallest value. Instead of using itemgetter()
he simply reverses the order of the values in the tuples so they naturally sort in the correct order.
If all you need is the single smallest value, this is an easy way:
from operator import itemgetter
lst = [20, 15, 27, 30]
i, value = min(enumerate(lst), key=itemgetter(1))
enumerate()
is the usual way in Python to pair up values from a list and their indices; it returns an iterator that yields up tuples like (i, value)
where value
is a value from the original sequence and i
is the index of that value within the sequence. min()
can take an iterator; the key=
argument is set to a function that ignores the paired index value and just finds the minimum second value (index 1) within each tuple.
min()
returns the tuple it finds with the min value and then we use tuple unpacking to assign the values to i
and value
.
The example shown is a list, but this would work with any sequence including an iterator:
from random import randint
def rseq(n=20):
for i in xrange(n):
yield randint(0, 101)
i, value = min(enumerate(rseq()), key=itemgetter(1))
Note that itemgetter(n)
is a factory that makes callable objects. With itemgetter(1)
you get a callable that returns the second item (index 1) in a sequence (in this case, a tuple). You could also write a function or a lambda
function to do the same thing:
def get1(x):
return x[1]
i, value = min(enumerate(lst), key=get1)
i, value = min(enumerate(lst), key=lambda x: x[1])