returning index of minimum in a list of lists

Steven Bethard steven.bethard at gmail.com
Wed Jun 21 12:52:54 EDT 2006


forman.simon at gmail.com wrote:
> JJLaRocque at gmail.com wrote:
>> Is there a simple python function to return the list index of the
>> minimum entry in a list of lists?
>> ie, for   [[3,3,3,3], [3,3,3,1], [3,3,3,3]]  to return 2,4.
>> Or, same question but just for a list of numbers, not a list of lists.
> 
> One way to do this is to generate (value, index-in-main-list,
> index-in-secondary-list) tuples and then just take the minimum.
> 
> def f(L):
>     '''Return indices of the first minimum value in a list of lists.'''
>     return min(
>         (n, i, j)
>         for i, L2 in enumerate(L)
>         for j, n in enumerate(L2)
>         )[1:]
> 
> L = [[3, 3, 3, 3], [3, 3, 3, 1], [3, 3, 3, 3]]
> 
> print f(L) # prints (1, 3)

I think this is probably the nicest solution.  Probably doesn't matter, 
but it may be worth noting that if you have more than one minimum value, 
this will return the one with the lowest indices (where indices are 
ordered lexicographically)::

 >>> L = [[3, 2, 1], [1, 2, 3], [2, 1, 3]]
 >>> min((n, i, j)
...     for i, L2 in enumerate(L)
...     for j, n in enumerate(L2))[1:]
(0, 2)

STeVe



More information about the Python-list mailing list