0
0
Pythonprogramming~5 mins

max() and min() in Python

Choose your learning style9 modes available
Introduction

The max() and min() functions help you find the biggest or smallest value in a group of items quickly.

Finding the highest score in a game.
Getting the lowest temperature from a list of daily temperatures.
Choosing the largest or smallest number from user inputs.
Comparing prices to find the cheapest or most expensive item.
Syntax
Python
max(iterable, *[, key, default])
min(iterable, *[, key, default])

# Or with multiple arguments:
max(arg1, arg2, *args, *[, key])
min(arg1, arg2, *args, *[, key])

You can give max() or min() either a list (or any iterable) or multiple separate values.

The optional key lets you decide how to compare items, like by length or a property.

Examples
Finds the biggest number in the list.
Python
max([3, 7, 2, 5])
Finds the smallest number among the separate values.
Python
min(10, 4, 8, 1)
Finds the longest word by length.
Python
max(['apple', 'banana', 'pear'], key=len)
Returns 0 if the list is empty, avoiding an error.
Python
min([], default=0)
Sample Program

This program finds the biggest and smallest numbers from a list, then finds the longest and shortest words from another list.

Python
numbers = [10, 20, 5, 40, 25]
print("Max number:", max(numbers))
print("Min number:", min(numbers))

words = ['cat', 'elephant', 'dog']
print("Longest word:", max(words, key=len))
print("Shortest word:", min(words, key=len))
OutputSuccess
Important Notes

If you use max() or min() on an empty list without a default, Python will give an error.

The key parameter is very useful when working with complex data like lists of strings or objects.

Summary

max() finds the biggest item; min() finds the smallest.

You can use them with lists or separate values.

Use key to customize how items are compared.