Python max() function


(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!


The max() function returns the largest of the input values.

Its syntax is as follows:

Parameter      Description
iterable(required) An iterable object like string, list, tuple etc.
default(optional) The default value to return if the iterable is empty.
key(optional) It refers to the single argument function to customize the sort order. The function is applied to each item on the iterable.

or

Parameter   Description
a, b, c ...Items to compare
key(optional) It refers to the single argument function to customize the sort order. The function is applied to each item on the iterable.

If max()  is called with an iterable, it returns the largest item in it. If the iterable is empty then the default value is returned, otherwise, a ValueError exception is raised.

If max()  is called with multiple arguments, it returns the largest one.

Let’s see some examples:

Example 1: Calling max() with an iterable

Example 2: Calling max() with multiple arguments

Trying to find largest value among the objects of different types causes an error.

Customing Sort Order

To customize the sort order we use the key named argument. It works exactly like the key named argument of the sorted()  function.

Here is an example where we use key argument to make the string comparision case-insentive.

The following is another example where we compare strings based on its length instead of their ASCII values.

There also exists a complementary function called min() which finds the lowest of the input values.


Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!


Leave a Reply

Your email address will not be published. Required fields are marked *