Next / Previous / Contents / TCC Help System / NM Tech homepage

20.26. max(): Largest element of an iterable

Given an iterable S that contains at least one element, max(S) returns the largest element of the sequence.

>>> max('blimey')
'y'
>>> max ( [-505, -575, -144, -288] )
-144
>>> max([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence

You can also pass multiple arguments, and max() will return the largest. In the example below, 'cheddar' is the largest because lowercase letters have higher codes than uppercase letters.

>>> max('Gumby', 'Lambert', 'Sartre', 'cheddar')
'cheddar'

If you want to redefine the comparison function, you may provide a keyword argument key=f, where f is a function that takes one argument and returns a value suitable for comparisons. In this example, we use the .upper() method of the str class to compare the uppercased strings, then return the original string whose uppercased value is largest.

>>> max('Gumby', 'Lambert', 'Sartre', 'cheddar', key=str.upper)
'Sartre'