min()
The built-in min()
function allows you to find the smallest value in an iterable or among multiple arguments. This function is versatile and can handle various data types, including numbers, strings, and more:
>>> min([3, 5, 9, 1, -5])
-5
min()
Signatures
min(iterable, *, key=None)
min(iterable, *, default, key=None)
min(arg1, arg2, *args, key=None)
Arguments
Argument | Description | Default Value |
---|---|---|
iterable |
An iterable object, such as a list, tuple, dictionary, or string. | Required argument |
default |
A value to return if the iterable is empty. | Keyword-only argument |
key |
A single-argument function to customize the comparison criteria. | None |
*args |
An undefined number of arguments. | - |
Return Value
- With a single iterable,
min()
returns the smallest item. - With multiple arguments,
min()
returns the smallest of the provided arguments. - If
default
is provided and the iterable is empty, thedefault
value is returned.
min()
Examples
With a list of integers as an argument:
>>> min([3.4, 5, 9, 1.2, -5])
-5
With a string as an argument:
>>> min("abcdefghijklmnopqrstuvwxyz")
'a'
With multiple string arguments:
>>> min("banana", "apple", "cherry")
'apple'
min()
Common Use Cases
The most common use cases for the min()
and max()
functions include the following:
- Finding the smallest number in a series of numbers.
- Identifying the earliest strings alphabetically.
- Extracting the minimum value from dictionary keys or values.
- Clipping values to a specified range in data processing.
min()
Real-World Example
Suppose you have a dictionary of product prices, and you want to identify the cheapest product. You can use min()
with the .items()
method and a lambda
function as the key
argument:
>>> prices = {
... "banana": 1.20,
... "pineapple": 0.89,
... "apple": 1.57,
... "grape": 2.45,
... }
>>> min(prices.items(), key=lambda item: item[1])
('pineapple', 0.89)
This example demonstrates how min()
can help you identify the least expensive products by using the dictionary’s values for comparison.
min()
in Custom Classes
You can support min()
in custom classes by implementing the .__lt__()
special methods. Here’s a quick example:
person.py
from datetime import date
class Person:
def __init__(self, name, birth_date):
self.name = name
self.birth_date = date.fromisoformat(birth_date)
def __repr__(self):
return (
f"{type(self).__name__}"
f"({self.name}, {self.birth_date.isoformat()})"
)
def __lt__(self, other):
return self.birth_date > other.birth_date
# Usage
jane = Person("Jane Doe", "2004-08-15")
john = Person("John Doe", "2001-02-07")
print(min(jane, john))
# Output: Person(Jane Doe, 2004-08-15)
This implementation allows you to use min()
and max()
on instances of the Person
class, comparing them by birthdate.
Related Resources
Tutorial
Python's min() and max(): Find Smallest and Largest Values
In this tutorial, you'll learn how to use Python's built-in min() and max() functions to find the smallest and largest values. You'll also learn how to modify their standard behavior by providing a suitable key function. Finally, you'll code a few practical examples of using min() and max().
For additional information on related topics, take a look at the following resources:
- Python "for" Loops (Definite Iteration) (Tutorial)
- For Loops in Python (Definite Iteration) (Course)
- Dictionaries in Python (Tutorial)
- Using Dictionaries in Python (Course)
- Python's Magic Methods: Leverage Their Power in Your Classes (Tutorial)
- Using Python's min() and max() (Course)
- The Python for Loop (Quiz)
- Python Dictionaries (Quiz)
- Python's Magic Methods in Classes (Course)
- Python's Magic Methods: Leverage Their Power in Your Classes (Quiz)