'Finding minimum tuple value satisfying a given condition

I have some tuples: (0,1,2), (3,4,4), (2,2,2) and I would like to find the minimum of the the zero index such that the second index equals 2. I have tried this using the min built-in function but it is giving me a syntax error.

min(data, key=lambda x: x if x[2] == 2)


Solution 1:[1]

Don't use the key parameter. If you want to ignore certain elements in finding the minimum, use filter() instead:

data = [(0,1,2), (3,4,4), (2,2,2)]

print(min(filter(lambda x: x[2] == 2, data)))

This outputs:

(0, 1, 2)

Solution 2:[2]

You're almost there. You should pass a generator expression to min which filters the list accordingly.

>>> data = [(0,1,2), (3,4,4), (2,2,2)]
>>> min((x for x in data if x[2] == 2), key=lambda x: x[0])
(0, 1, 2)

Of course, the default behavior of min on a list of tuples of numbers like this means that explicitly keying min on the first element of the tuple is not necessary, though it does possibly make the intent of the code more explicit.

min(x for x in data if x[2] == 2)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BrokenBenchmark
Solution 2