Search code examples
pythonpython-3.xiterator

Get set with smallest 3rd value in python


I have an array. This iterator-object including multiple tuples of length 3. I would like to pick a tuple with the smallest third value.

for example (I just wrote it down as a list but it's not a list)

a = [(1, 5, 4), (2, 5, 0.4), (3, 4, 0.4), (1, 9, 0.3)]

the output should be:

(1, 9, 0.3)


Solution

  • Use min with a custom key fetching the 3rd value

    values = [(1, 5, 4), (2, 5, 0.4), (3, 4, 0.4), (1, 9, 0.3)]
    
    min_tuple = min(values, key=lambda x: x[2])
    print(min_tuple)  # (1, 9, 0.3)