In this tutorial, we will delve into one of Python’s built-in functions – the
max() function. This function is used to return the item with the highest value or the item with the maximum value if parameters are provided.
Basic Usage of max()
The basic syntax for using
max() is as follows:
max(iterable, *[, key, default]) max(arg1, arg2, *args[, key])
The first form returns the largest item in an iterable (for example a list or a set). The second form returns the largest of two or more arguments.
Example 1: Using max() with Lists
numbers = [5, 11, 9, 33, 14] print(max(numbers)) # Output: 33
In this example,
max() returns ’33’, which is the highest number in our list.
Example 2: Using max() with Strings
words = ["apple", "banana", "cherry"] print(max(words)) # Output: cherry
In this case,
max() returns ‘cherry’, which is considered ‘largest’ based on lexicographical order in strings.
The Key Parameter in max()
You can provide a key function that helps to compute comparisons. This function will be applied to each element before comparison.
names = ['Bob', 'Alice', 'Charlie'] print(max(names, key=len)) # Output: Charlie
max() returns ‘Charlie’, which is the longest string in our list when we use len as the key function.
The Default Parameter in max()
If the provided iterable is empty,
max() will return a ValueError. To avoid this, you can specify a default value to be returned instead.
numbers =  print(max(numbers, default=0)) # Output: 0
In this case, since our list is empty,
max() returns ‘0’, which we specified as our default value.
max() function is a versatile tool that can help you find maximum values from various data types. By understanding how to use it effectively with its parameters like key and default, you can make your code more efficient and clean.
We hope this tutorial has been helpful in enhancing your understanding of Python’s built-in functions. Happy coding!