theguyty - 27 days ago 5
Python Question

# Python - Selecting smallest y from a list of tuples and keeping x

I am trying to iterate through a list of tuples like this:

``````[(0, 0.0083553666846612491), (1, 0.0054999681509501821)]
``````

and find the smallest value on the right hand side of the tuple and then save the accompanying left hand side value to a variable.

What would the best way to go about this problem be?

Answer

You can use the `key` argument to the `min()` function to find the tuple with the smallest second value:

``````>>> l = [(0, 0.0083553666846612491), (1, 0.0054999681509501821)]
>>> smallest = min(l, key=lambda x: x[1])[0]
>>> smallest
1
``````

Here a lambda expression is used to select the second item of each tuple and `min` uses that value in its comparisons. `min()` returns the full tuple, so you can extract the first item using `[0]`.

You can also use `operator.itemgetter`:

``````>>> from operator import itemgetter
>>> smallest = min(l, key=itemgetter(1))[0]
>>> smallest
1
``````
Comments