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:

Python
>>> max([3, 5, 9, 1, -5])
9

max() Signatures

Python Syntax
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, the default value is returned.

max() Examples

With a list of numeric values as an argument:

Python
>>> max([3.4, 5, 9, 1.2, -5])
9

With a string as an argument:

Python
>>> max("abcdefghijklmnopqrstuvwxyz")
'z'

With multiple string arguments:

Python
>>> 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:

Python
>>> 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:

Python 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().

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 7, 2024 • Reviewed by Dan Bader