max() is a built-in function in Python used to return the maximum value from an iterable or the maximum value among multiple parameters.

Function Syntax

The max() function has two forms:

1. Accepts an Iterable

max(iterable, *[, key, default])

Parameters:

  • iterable: An iterable object, such as a list, tuple, or set.
  • key: Optional parameter, specifies a function as the comparison key, defaults to None.
  • default: Optional parameter, default value returned when iterable is empty.

2. Accepts Multiple Separate Parameters

max(arg1, arg2, *args[, key])

Parameters:

  • arg1, arg2, *args: Objects to compare.
  • key: Optional parameter, specifies a function as the comparison key.

max() Function Examples

Here's an example demonstrating how to use the max() function to get the maximum value from a list:

my_list = [3, 7, 1, 9, 2]
maximum = max(my_list)
print(maximum)  # 9

Compare sizes of multiple objects:

a = 5
b = 9
c = 3

maximum = max(a, b, c)
print(maximum)  # 9

Specify key to get the value with the largest absolute value in the list:

my_list = [-1, 66, 7, -99, 3]
# Number with largest absolute value
maximum = max(my_list, key=abs)
print(maximum)  # -99

Specify key to get the longest string in the list:

words = ['what', 'are', 'you', 'doing']

print(max(words, key=len))  # 'doing'

Use key for custom comparison rules:

# Oldest person
people = [
    {'name': 'Zhang', 'age': 18},
    {'name': 'Li', 'age': 35},
    {'name': 'Wang', 'age': 60}
]
oldest = max(people, key=lambda p: p['age'])
print(oldest['name'])  # 'Wang'


# Find coordinate farthest from origin
import math

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
    def __str__(self):
        return f'({self.x},{self.y})'
        
def distance_from_origin(p):
    return math.sqrt(p.x**2 + p.y**2)

points = [Point(1, 2), Point(3, 4), Point(5, 6)]

max_point = max(points, key=distance_from_origin)
print(max_point)

When dealing with empty sequences, you need to specify default, otherwise a ValueError exception will be raised:

empty = []
print(max(empty))  # ValueError
print(max(empty, default=0))  # 0