Maximum value from a list of lists and its index

zaman sakib picture zaman sakib · Aug 2, 2015 · Viewed 7.4k times · Source
li = [[1,2], [2,3], [7,6]]

How can I find the max value and its index efficiently? Suppose for li I want:

max_value = 7

max_index = (2, 0)

I can do this as below:

max_value = 0
for row_idx, row in enumerate(alignment_matrix):    
    for col_idx, col in enumerate(row):
        if col > max_value:
            max_value = col
            max_index = (row_idx, col_idx)

But I need an efficient way without using too many unnecessary variables.

Answer

falsetru picture falsetru · Aug 2, 2015

Using max and generator expression, you can express it more shortly:

max_value, max_index = max((x, (i, j))
                           for i, row in enumerate(li)
                           for j, x in enumerate(row))

But, time complexity is same because this one also uses nested loop.

UPDATE

As @jonrsharpe pointed, in the case of duplicate max_values, above solution will give you the largest index at which the value found.

If that's not what you want, you can pass key function argument to max to customize the behavior:

max_value, max_index = max(((x, (i, j))
                            for i, row in enumerate(li)
                            for j, x in enumerate(row)),
                           key=lambda (x, (i, j)): (x, -i, -j))