Python max() function
The max()
function in Python returns the largest item in an iterable (such as a list, tuple, or string) or the largest of two or more arguments.
Syntax
iterable
: An iterable (e.g., list, tuple, or string) from which the maximum value is found.arg1, arg2, *args
: If multiple arguments are passed,max()
returns the largest of these values.key
(optional): A function that specifies how to compare the items. The comparison is done based on the value returned by the function for each item.default
(optional): If the iterable is empty and this argument is provided, it returns thedefault
value.
Return Value
- Returns the largest item from the provided iterable or among the provided arguments.
- If the iterable is empty and no
default
is provided, aValueError
is raised.
Examples
Using
max()
with a list of numbers:Using
max()
with multiple arguments:Using
max()
with a string: When used with a string,max()
returns the character with the highest Unicode value.Using
max()
with a key function: You can use thekey
argument to specify a function that extracts a comparison key from each element.Using
max()
with tuples:Using
max()
with an empty iterable anddefault
: If the iterable is empty, you can provide adefault
value to avoid an error.Finding the maximum in a dictionary by values: You can use
max()
with akey
to find the key with the largest value.
Summary
- The
max()
function finds the largest value in an iterable or among several arguments. - You can customize the comparison using the
key
argument, and provide adefault
value for empty iterables. - It works with various data types like numbers, strings, tuples, and even dictionaries.