min() and max()
min() returns the smallest value and max() the largest, either among several arguments or inside an iterable.
Used in 71 lessons of the course, from 00.01.
min() and max() compare values and give you back one: the smallest or the largest.
You can pass several arguments, like min(3, 7), or a single iterable, like max([3, 7, 5]).
A very common use is setting a limit. min(n, 10) never gives more than 10. max(n, 0) never gives less than 0. It is written this way because it is shorter and clearer than an if.
In lesson 00.01 it looks like this:
n = min(n, len(GLOSSARY))
Here n is reduced to the size of GLOSSARY if it is bigger. That way sample() never receives a k larger than the population and does not raise ValueError.
If the iterable is empty, they raise ValueError, unless you pass default=.
Reach for it when: you need the smallest or largest of some values, or when you want to clamp a number to a ceiling or a floor.
Examples
Common mistake
scores = [] print(max(scores))
Why: max() cannot pick a value from an empty sequence.
How to write it: Pass a fallback value: max(scores, default=0).
Common mistake
print(max("9", "10"))Why: Strings are compared character by character, so "9" is greater than "10".
How to write it: Convert to numbers first: max(int("9"), int("10")).
