Python max() With Examples

Python max() function returns the largest item in the iterable or the largest of two or more arguments.

Python max()

Python max() function syntax is:

  • If there is only one argument, it should be an iterable such as string, list, tuple etc. The largest item in the iterable is returned.
  • If two or more arguments are provided, largest of them will be returned.
  • We can specify key argument function to be used for identifying the largest item. This is an optional argument and mostly used when arguments are custom objects.
  • The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, ValueError exception is raised.
  • If multiple largest element is found, then the first one is returned.

Python max() function examples

Let’s look at some examples of max() function.

max() with string

When max() function is used with string argument, the character with maximum unicode value is returned.

Output:

max() with tuple

Output: 4

max of list

Output: 3

max() of objects

When we want to use max() function with custom objects, we have to provide key function argument to be used for comparing the objects.

Output: Data[2]

If we don’t provide a key function as an argument, we will get the following error.

max() with empty iterable and default value

Output: 20

max() function with multiple arguments

Output: 4

max() with arguments and key function

Output: abc

max() with multiple iterables

Output: [5, 15, 40, 25]

If we don’t provide key function as an argument, the output will be [10, 20, 30]. It’s because the comparison will be done between the elements of the iterable elements one by one. When an element with the larger value is found, the iterable with that element will be returned.

max() with multiple iterables of objects

Output:

Notice that with multiple arguments, iterables are treated as objects. If we don’t specify key function, we will get error message as TypeError: '>' not supported between instances of 'Data' and 'Data'. Earlier it worked with integer elements because they support > and Summary

Summary

Python max() function helps us in identifying the largest element in the iterable or largest item from multiple arguments. It’s useful because we can specify our own function to be used for comparison through key argument.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: