The min() built-in function returns the smallest item from an iterable or the smallest of two or more positional arguments.
Extremum Selection & Key Evaluation: min() evaluates comparisons in linear O(N) time without sorting the underlying container. It accepts an optional key callable (such as len or str.lower) to compute proxy comparison values, and a default parameter to prevent ValueError on empty collections. To find the highest item, see companion function max(), or sort collections with sorted().
The min() function supports two operational forms:
# Formal syntax of built-in min()
# Form 1: Single iterable with optional default and key
min_item = min(iterable, *, key=None, default=sentinel)
# Form 2: Two or more positional arguments with optional key
min_item = min(arg1, arg2, *args, key=None)
| Parameter | Type Accepted | Behavioral Details |
|---|---|---|
iterable or arg1, arg2, *args |
Iterable[T] or multiple objects |
A single collection (list, tuple, string, set) OR 2+ distinct arguments. |
key |
Callable (1 arg) or None |
Optional proxy function extracting a comparison key from each element. Defaults to None. |
default |
Any object | Returned when iterable is empty. Valid only with single iterable form. |
| Return Value | Element of iterable |
Returns the item yielding the smallest comparison value. If multiple items are equal, returns the first encountered. |
You can pass individual numbers as positional arguments or pass an entire container as a single argument:
# 1. Finding minimum from multiple positional arguments
print("min(6, 9): ", min(6, 9))
print("min(14, 3, 8, 22, -5): ", min(14, 3, 8, 22, -5))
# 2. Finding minimum from an iterable list or tuple
numbers = [6, 1, 2, 3, 4, 5]
print("min([6, 1, 2, 3, 4, 5]):", min(numbers))
coords = (12.5, 4.2, 8.9)
print("min((12.5, 4.2, 8.9)): ", min(coords))
Output:
min(6, 9): 6
min(14, 3, 8, 22, -5): -5
min([6, 1, 2, 3, 4, 5]): 1
min((12.5, 4.2, 8.9)): 4.2
Strings are compared by Unicode code points. Use key=str.lower for case-insensitive checks:
# Lexicographical comparison based on Unicode code points
# Uppercase ASCII ('A'..'Z', 65..90) precede lowercase ('a'..'z', 97..122)
title_words = ['Hello', 'Welcome', 'To', 'Plus2net']
print("Title case min: ", min(title_words)) # 'Hello'
mixed_words = ['hello', 'Welcome', 'to', 'plus2net']
print("Mixed case min: ", min(mixed_words)) # 'Welcome' (ASCII 'W' = 87 < 'h' = 104)
# Case-insensitive comparison using key=str.lower
print("Case-insensitive:", min(mixed_words, key=str.lower)) # 'hello'
Output:
Title case min: Hello
Mixed case min: Welcome
Case-insensitive: hello
Passing a dictionary directly evaluates its keys. To find the key of the lowest value, use key=dict.get:
# Dictionaries evaluate KEYS by default, not values
scores = {'Raju': 45, 'Ronn': 56, 'Tom': 50}
print("Min key alphabetically:", min(scores)) # 'Raju'
# To find the key with the minimum value, pass key=scores.get
lowest_student = min(scores, key=scores.get)
print("Lowest score student: ", lowest_student, "with score", scores[lowest_student])
# To find the minimum (key, value) tuple:
min_pair = min(scores.items(), key=lambda item: item[1])
print("Lowest score pair: ", min_pair)
Output:
Min key alphabetically: Raju
Lowest score student: Raju with score 45
Lowest score pair: ('Raju', 45)
Comparing multiple sequences evaluates elements position-by-position until an inequality is found:
# Positional comparison across multiple sequences
# Comparison proceeds from left to right element-by-element
list1 = [4, 7, 8, 9]
list2 = [4, 1, 1]
list3 = [4, 1, -3]
# Compares index 0 (all 4), then index 1 (1 < 7), then index 2 (-3 < 1)
print("Positional list min:", min(list1, list2, list3))
# Comparing by aggregated property using key=sum or key=len
print("Min by sum: ", min(list1, list2, list3, key=sum))
print("Min by length: ", min(['alpha', 'beta', 'pi'], key=len))
Output:
Positional list min: [4, 1, -3]
Min by sum: [4, 1, -3]
Min by length: pi
Calling min() on an empty collection raises ValueError. The default argument provides a safe fallback:
# Suppressing ValueError on empty iterables using default
empty_log = []
# Without default, min([]) raises ValueError: min() arg is an empty sequence
try:
min(empty_log)
except ValueError as err:
print("ValueError caught:", err)
# Safe pattern: providing a default fallback value
safe_min = min(empty_log, default=0)
print("Safe min with default: ", safe_min)
safe_record = min(empty_log, default={"price": 0.0})
print("Safe record fallback price:", safe_record["price"])
Output:
ValueError caught: min() arg is an empty sequence
Safe min with default: 0
Safe record fallback price: 0.0
Below are real-world recipes utilizing min() for e-commerce catalog queries and value clamping:
# Recipe A: Finding cheapest item in a catalog
catalog = [
{"item": "Desk Lamp", "price": 35.00},
{"item": "Mousepad", "price": 9.99},
{"item": "Cable Pack","price": 12.00},
]
cheapest = min(catalog, key=lambda p: p["price"])
print(f"Cheapest: {cheapest['item']} at {cheapest['price']}")
# Recipe B: Clamping values: max(low, min(val, high))
def clamp(val: float, low: float, high: float) -> float:
return max(low, min(val, high))
print("Clamped 150 into [0, 100]:", clamp(150, 0, 100))
print("Clamped -25 into [0, 100]:", clamp(-25, 0, 100))
Output:
Cheapest: Mousepad at 9.99
Clamped 150 into [0, 100]: 100
Clamped -25 into [0, 100]: 0
TypeError: '<' not supported between instances. Provide a homogeneous key function like key=str if needed.default when passing multiple positional arguments (e.g. min(1, 2, default=0)) raises a TypeError. The default parameter is only valid when evaluating a single iterable.min() consistently returns the first one encountered in the iterable.# Pitfall 1: Unorderable mixed types in Python 3
try:
min([10, "apple", 5])
except TypeError as err:
print("TypeError caught:", err)
# Pitfall 2: Confusing multiple arguments with a single iterable
print("Three args: ", min(1, 2, 3))
print("Single list arg:", min([1, 2, 3]))
Output:
TypeError caught: '<' not supported between instances of 'str' and 'int'
Three args: 1
Single list arg: 1
Practice extremum search, dictionary key evaluations, and value clamping in our companion Jupyter Notebook:
Explore interactive code cells, benchmark key function performance, build numeric clamping utilities, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify min() mechanics:
def test_min_mechanics():
# 1. Positional and iterable
assert min(10, 20, 5) == 5
assert min([10, 20, 5]) == 5
# 2. Key function
words = ["apple", "pie", "banana"]
assert min(words, key=len) == "pie"
# 3. Default fallback on empty collection
assert min([], default=999) == 999
# 4. Dictionary value search
data = {"a": 30, "b": 10, "c": 20}
assert min(data, key=data.get) == "b"
print("All min() unit assertions passed! 100% verified.")
test_min_mechanics()
Output:
All min() unit assertions passed! 100% verified.
Returns the largest item from an iterable or series of arguments.
Sorts all elements of an iterable using stable Timsort ordering.
Sums numeric elements in an iterable with an optional starting value.
Calculates the non-negative magnitude of a number or complex vector.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.