Search code examples
pythonlistpython-3.5minenumerate

python3, minimum in nested list keeping index using enumerate


nlist = [ [10, 6], [12,3], [13,1] ]

I am trying to find the list element with the smallest second subelement, i.e. I want to have [13, 1] returned - this I can achieve with:

min(nlist, key = lambda x: x[1])

If I also want the to get the index in nlist of the results by using the enumerate function I get cannot figure out to rewrite the lambda to open the enumerate object. This of course does not work:

min(enumerate(nlist), key = lambda x: x[1])

The expected result should be something like (index, min_element):

(2, [13, 1])

Perhaps this Finding the index of an item given a list containing it in Python has the solution embedded somewhere (not nested lists).


Solution

  • enumerate returns a tuple containing the index and the element. You can apply the subscript operator (i.e., [1]) to it to retrieve the element and use it in your lambda:

    min(enumerate(nlist), key = lambda x: x[1][1])