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
min()andmax()look at every item once and return the smallest or largest value.temperatures.index(value)gives the position of the first item equal tovalue. Positions start at 0, so we add 1 to get "day 3".- Both functions also work on strings, where "smallest" means first in alphabetical order:
min(["Linus", "Ada", "Grace"])is"Ada".
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