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

max(iterable, *[, key, default]) max(arg1, arg2, *args[, key])
  • 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 the default 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, a ValueError is raised.

Examples

  1. Using max() with a list of numbers:

    numbers = [1, 5, 3, 9, 2] print(max(numbers)) # Output: 9
  2. Using max() with multiple arguments:

    print(max(10, 20, 30)) # Output: 30
  3. Using max() with a string: When used with a string, max() returns the character with the highest Unicode value.

    print(max("hello")) # Output: 'o'
  4. Using max() with a key function: You can use the key argument to specify a function that extracts a comparison key from each element.

    words = ["apple", "banana", "cherry"] print(max(words, key=len)) # Output: 'banana' (longest word)
  5. Using max() with tuples:

    points = [(2, 5), (1, 9), (4, 7)] print(max(points)) # Output: (4, 7) (compares based on the first value)
  6. Using max() with an empty iterable and default: If the iterable is empty, you can provide a default value to avoid an error.

    empty_list = [] print(max(empty_list, default=0)) # Output: 0
  7. Finding the maximum in a dictionary by values: You can use max() with a key to find the key with the largest value.

    scores = {"Alice": 10, "Bob": 20, "Charlie": 15} print(max(scores, key=scores.get)) # Output: 'Bob' (largest score)

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 a default value for empty iterables.
  • It works with various data types like numbers, strings, tuples, and even dictionaries.