In this tutorial, we will delve into one of Python’s built-in functions, the max()
function. This function is used to return the largest item in an iterable or the largest of two or more arguments.
Basic Usage of max()
The basic syntax for using the max()
function is as follows:
max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])
This means that you can use max()
in two ways:
- With a single iterable argument: It returns the largest item in the iterable.
- With two or more arguments: It returns the largest argument.
An Example with a Single Iterable Argument
numbers = [12, 25, 33, 50, 75]
print(max(numbers))
# Output: 75
In this example, we have passed a list of numbers to max()
. The function has returned ’75’, which is the highest number in our list.
An Example with Two or More Arguments
print(max(15, 20))
# Output: 20
In this case, we have passed two numbers directly to max()
. The function has returned ’20’, which is higher than ’15’.
The Key Parameter and Default Parameter
The ‘key’ parameter allows you to provide a function of one argument that is used to extract a comparison key from each input element. The ‘default’ parameter is what the max() function returns if the iterable is empty.
An Example with Key Parameter
students = [
{"name": "Emma", "grade": 90},
{"name": "Laura", "grade": 85},
{"name": "Dan", "grade": 92}
]
highest_grade_student = max(students, key=lambda student: student["grade"])
print(highest_grade_student)
# Output: {'name': 'Dan', 'grade': 92}
In this example, we have passed a list of dictionaries representing students. We’ve also provided a lambda function as the key which tells Python to use the ‘grade’ value for comparisons.
An Example with Default Parameter
numbers = []
print(max(numbers, default="List is empty"))
# Output: List is empty
Here, since our list is empty and we have provided a default value, max()
returns our default value instead of raising an error.
Conclusion
The Python max()
function is an incredibly useful tool for finding the maximum value in an iterable or between two or more arguments. With its optional parameters like ‘key’ and ‘default’, it offers flexibility that can be very handy in many situations.