max() function in python is used to find

  • the largest value of two or more numbers passed as arguments
  • lexicographically largest value if strings are passed as arguments
  • the largest item an any iterable like list, set, etc.

max() Syntax and Parameters

In general max() function has two kinds of syntax. we can pass multiple values separately or whole as an iterable as argument to the max() function.

If multiples values are passed then the largest of them will be returned.

Python max() function parameters
ParameterConditionDescription
val1,val2,val3…RequiredValues that need to be compared
keyOptionalA function specify custom comparison criteria to find maximum value.
Default value is None.

If an iterable is passed then the largest value of the iterable is returned.

Python max() function parameters
ParameterConditionDescription
iterableRequiredAny iterable, with one or more items to compare
keyOptionalA function specify custom comparison criteria to find maximum value.
Default value is None.
defaultOptionalA value to return if the iterable is empty.
Default value is False.

let see some examples of max() function.

Examples

Finding maximum when multiples values are passed as arguments.

Finding maximum when an iterable is passed as an argument.

when not sure that iterable cannot be empty then better to provide default value as well to the max function to prevent ValueError exception.

Using len as key parameter to get longest string as the max value.

We can also use user-defined lambda function as key to get desired value as the max result.

Comment below if you have any doubts or suggestions.

Leave a Reply