0
0
PythonHow-ToBeginner · 3 min read

How to Use min and max with key in Python

In Python, you can use the min() and max() functions with the key parameter to specify a function that determines the value used for comparison. This lets you find the minimum or maximum item based on custom rules, like length or a specific attribute.
📐

Syntax

The min() and max() functions accept an optional key argument, which is a function applied to each item to determine its comparison value.

  • min(iterable, key=function)
  • max(iterable, key=function)

The key function takes one argument and returns a value used to compare items.

python
min(iterable, key=function)
max(iterable, key=function)
💻

Example

This example finds the shortest and longest word in a list by using len as the key function.

python
words = ['apple', 'banana', 'cherry', 'date']
shortest = min(words, key=len)
longest = max(words, key=len)
print(f"Shortest word: {shortest}")
print(f"Longest word: {longest}")
Output
Shortest word: date Longest word: banana
⚠️

Common Pitfalls

One common mistake is forgetting to use the key parameter and trying to compare complex objects directly, which can cause errors or unexpected results.

Also, the key function should return a value that can be compared, like a number or string.

python
people = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]

# Wrong: causes error because dicts are not directly comparable
# youngest = min(people)  # This will raise an error

# Right: use key to compare by 'age'
youngest = min(people, key=lambda person: person['age'])
print(youngest)
Output
{'name': 'Bob', 'age': 25}
📊

Quick Reference

Tips for using min and max with key:

  • Use key to customize comparison logic.
  • The key function should return a comparable value.
  • Works with any iterable like lists, tuples, or sets.
  • Can use built-in functions like len or custom lambdas.

Key Takeaways

Use the key parameter in min() and max() to customize how items are compared.
The key function should return a value that Python can compare, like a number or string.
Without key, min() and max() compare items directly, which may cause errors for complex objects.
You can use built-in functions like len or write your own function or lambda for key.
min() and max() work with any iterable, such as lists, tuples, or sets.