Python - find minimum value using special comparator


Python Clean Code Tip:

Use min to find an element with minimal value inside an iterable. You can provide a custom function as a key argument to serve as a key for the min comparison.

temperatures = [22.3, 28.7, 15.3, 18.2]

# without min
min_temperature = 10000

for temperature in temperatures:
    if temperature < min_temperature:
        min_temperature = temperature

print(min_temperature)
# => 15.3


# with min
min_temperature = min(temperatures)
print(min_temperature)
# => 15.3


# using key
users = [
    {"username": "johndoe", "height": 1.81},
    {"username": "marrydoe", "height": 1.69},
    {"username": "joedoe", "height": 2.03},
]
shortest_user = min(users, key=lambda user: user["height"])
print(shortest_user)
# {'username': 'marrydoe', 'height': 1.69}