Python max() Function – Tutorial with Examples

The Python max() function is a built-in function that returns the largest item in an iterable or the largest of two or more arguments. The iterable can be a list, tuple, set, or any other collection that can be iterated upon. If two or more arguments are provided, it returns the largest of the arguments.

Syntax

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

Parameters

  • iterable – The iterable to find the maximum item in.
  • arg1, arg2, *args – The arguments to find the maximum of.
  • key – (Optional) A function that returns a value used to compare elements in the iterable or the arguments.
  • default – (Optional) The value to return if the iterable is empty.

Return Value

The max() function returns the largest item in the iterable or the largest of the arguments.

Examples

Example 1: Finding the maximum item in a list

lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
print(max(lst))

Output:

9

In this example, we have defined a list lst of numbers. Then we have used the max() function to find the maximum item in the list and print it. The output is 9, which is the largest number in the list.

Example 2: Finding the maximum of two or more arguments

print(max(1, 2, 3, 4, 5))
print(max(5, 4, 3, 2, 1))

Output:

5
5

In this example, we have used the max() function to find the maximum of two or more arguments. In the first call, we have provided five numbers as arguments, and in the second call, we have provided the same five numbers in reverse order. The output of both calls is 5, which is the largest of the arguments.

Example 3: Using the key parameter

lst = ['apple', 'banana', 'cherry', 'date']
print(max(lst, key=len))

Output:

banana

In this example, we have defined a list lst of strings. Then we have used the max() function with the key parameter to find the maximum string based on its length. The key parameter is a function that returns a value used to compare elements in the iterable. In this case, the function len returns the length of the strings. The output is ‘banana’, which is the longest string in the list.

Use Cases

The max() function is useful in many different situations where you need to find the largest item in a collection or the largest of two or more arguments. Some of the use cases are:

  • Finding the maximum value in a list of numbers
  • Finding the longest string in a list of strings
  • Finding the largest item in a tuple, set, or any other iterable
  • Comparing the values of two or more arguments and finding the largest

The max() function is a simple and efficient way to find the largest item in a collection or the largest of two or more arguments, making it a useful tool in many different programming scenarios.

Leave a Reply

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