Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to extract a tuple from list of tuples with minimum value of element

I am having list of tuple from which I want the tuple with the minimum value at index 1. For example, if my list is like:

a =[('a', 2), ('ee', 3), ('mm', 4), ('x', 1)]

I want the returned tuple to be ('x', 1).

Currently I am using sorted function to get this result like:

min=sorted(a, key=lambda t: t[1])[0]

Is there better ways to do it? Maybe with min function?

like image 698
Dork Avatar asked Nov 03 '25 01:11

Dork


2 Answers

You may use min() function with key parameter in order to find the tuple with minimum value in the list. There is no need to sort the list. Hence, your min call should be like:

>>> min(a, key=lambda t: t[1])
('x', 1)

Even better to use operator.itemgetter() instead of lambda expression; as itemgetter are comparatively faster. In this case, the call to min function should be like:

>>> from operator import itemgetter

>>> min(a, key=itemgetter(1))
('x', 1)

Note: min() is a in-built function in Python. You should not be using it as a variable name.

like image 92
Moinuddin Quadri Avatar answered Nov 04 '25 16:11

Moinuddin Quadri


This will also work:

min([x[::-1] for x in a])[::-1]
# ('x', 1)
like image 45
Sandipan Dey Avatar answered Nov 04 '25 18:11

Sandipan Dey