min()
min(iterable, *[, key, default]) The min() function returns the smallest item in an iterable or the smallest of two or more arguments. It accepts an optional key parameter for custom comparison logic and a default value for empty iterables.
Syntax
min(iterable, *[, key, default])
min(arg1, arg2, *args)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| iterable | iterable | — | An iterable containing comparable elements |
| *args | objects | — | Multiple arguments to compare (instead of iterable) |
| key | callable | None | A function that returns a value to compare |
| default | object | None | Value to return if the iterable is empty |
Examples
Basic usage with a list
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
result = min(numbers)
print(result)
# 1
Multiple arguments
result = min(3, 1, 4, 1, 5, 9, 2, 6)
print(result)
# 1
Using key parameter
words = ["apple", "banana", "cherry", "date"]
shortest = min(words, key=len)
print(shortest)
# 'date'
Using default for empty iterable
empty_list = []
result = min(empty_list, default=0)
print(result)
# 0
Finding minimum in a list of dictionaries
products = [
{"name": "Widget", "price": 25},
{"name": "Gadget", "price": 15},
{"name": "Gizmo", "price": 30}
]
cheapest = min(products, key=lambda x: x["price"])
print(cheapest)
# {'name': 'Gadget', 'price': 15}
Common Patterns
Finding the key with minimum value
word_lengths = {"apple": 5, "banana": 6, "cherry": 6}
shortest_word = min(word_lengths, key=word_lengths.get)
print(shortest_word)
# 'apple'
Conditional min
numbers = [1, -5, 3, -2, 7, -1]
min_positive = min(n for n in numbers if n > 0)
print(min_positive)
# 1
Errors
-
ValueError: If the iterable is empty and no default is provided:
min([]) # ValueError: min() arg is an empty sequence -
TypeError: If comparing incompatible types:
min([1, "a"]) # TypeError: < not supported between instances