max()

Returns the largest item in a collection, or the largest of several arguments.

Returns
The largest item.
On this page

Example

#
Python
students = [
    {"name": "Emma", "points": 1240},
    {"name": "Jack", "points": 980},
]

best = max(students, key=lambda s: s["points"])
print(best["name"])

progress = 130
print(max(0, min(progress, 100)))
Resultsaved result, you can check it
Emma
100

Definition and usage

#

max() works like min(), but returns the largest item. It takes a collection, or several separate arguments.

With the key parameter you can find the object with the largest value of a chosen field, for example the best student, without sorting the whole list.

Combining max() and min() lets you clamp a value to a range: max(0, min(value, 100)) always returns a number from 0 to 100.

Syntax

#
Syntax
max(iterable, key=None, default=…)
max(a, b, *args, key=None)

Parameters

#
  • iterable

    a collection

    The items to compare, or several separate arguments.
  • key

    function, optional

    The comparison criterion.
  • default

    optional

    The value returned for an empty collection.

Good practices

#
  • When you only need the best item, max(key=...) is faster than sorting the whole list.
  • The pattern max(low, min(value, high)) clamps a value to a range.

Related entries

#

Spotted a mistake or missing an example? Write to us.