PythonMastery
Python programs · Lists · beginner

Find the minimum and maximum of a list in Python

Find the smallest and largest number in a list with min() and max(), then the same thing with a loop, and what to do with an empty list.

min() gives the smallest item in a list and max() gives the largest. Writing the same thing with a loop shows how they work.

The program

python
temperatures = [21.5, 18.0, 25.3, 19.8, 23.1]

print("Lowest:", min(temperatures))
print("Highest:", max(temperatures))
print("Hottest day is number", temperatures.index(max(temperatures)) + 1)
output
Lowest: 18.0
Highest: 25.3
Hottest day is number 3

How it works

Another way: by hand

Start with the first item as both the smallest and the largest so far, then compare every other item with them:

python
numbers = [3, 1, 4, 1, 5, 9, 2, 6]

smallest = numbers[0]
largest = numbers[0]
for n in numbers[1:]:
    if n < smallest:
        smallest = n
    if n > largest:
        largest = n

print("Min:", smallest)
print("Max:", largest)
output
Min: 1
Max: 9

An empty list

min([]) raises a ValueError, because there is no smallest item. Give a default value to get that value instead:

python
print(min([], default=None))
print(max([], default=0))
output
None
0

Learn the idea: Lists & Sequences, Loops: for, while, and the Pythonic Patterns