max()
The built-in max()
function allows you to find the largest values in an iterable or among multiple arguments. This function is versatile and can handle various data types, including numbers, strings, and more:
>>> max([3, 5, 9, 1, -5])
9
max()
Signatures
max(iterable, *, key=None)
max(iterable, *, default, key=None)
max(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,
max()
returns the largest value or item. - With multiple arguments,
max()
returns the largest of the provided arguments. - If
default
is provided and the iterable is empty, thedefault
value is returned.
max()
Examples
With a list of numeric values as an argument:
>>> max([3.4, 5, 9, 1.2, -5])
9
With a string as an argument:
>>> max("abcdefghijklmnopqrstuvwxyz")
'z'
With multiple string arguments:
>>> max("banana", "apple", "cherry")
'cherry'
max()
Common Use Cases
The most common use cases for the max()
functions include:
- Finding the largest numbers in a series of numbers.
- Identifying the latest strings alphabetically.
- Extracting the maximum values from dictionary keys or values.
- Clipping values to a specified range in data processing.
max()
Real-World Example
Suppose you have a dictionary of product prices and want to identify the most expensive product. You can use max()
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,
... }
>>> max(prices.items(), key=lambda item: item[1])
('grape', 2.45)
This example demonstrates how max()
can help you identify the most expensive products by using the dictionary’s values for comparison.
max()
in Custom Classes
You can support max()
in custom classes by implementing the .__gt__()
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 __gt__(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(max(jane, john)) # Output: Person(John Doe, 2001-02-07)
This implementation allows you to use 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)