How to find min of second element in the list

Viewed 1215

I have a list below:

a = [ [8, 12], [13, 9], [2, 5], [1, 10], [13, 13] ]

How do I find 5 of a[2][1]. I want to find the minimum value of second element of the sub-list.

This is my code:

min = a[0][1]
for i in range(len(a)):
  temp = a[i][1]
  if temp < min:
    min = temp

What is a good way (with fewer lines of code) to implement this code?

3 Answers

you could use the built-in function min with parameter key:

a = [ [8, 12], [13, 9], [2, 5], [1, 10], [13, 13] ]
min(a, key=lambda x: x[1])[1]

output:

5

You can make a generator that obtains the second element for each sublist with:

sub[1] for sub in data

So we can pass this to the min(..) function:

min(sub[1] for sub in data)

If not all sublists have at least two elements, we can add a filter conditon:

min(sub[1] for sub in data if len(sub) > 1)

You can see it in another way

  • filter to get only the seconds elements, here's some ways

    seconds = [v[1] for v in a]
    seconds = map(itemgetter(1), a)
    
  • get the min in this

    min_val = min(seconds)
    

Shorted result

min_val = min(map(itemgetter(1), a))
Related