Python Practice › List Programs › Program 5
Minimum and maximum
Write a Python program to find the smallest and largest elements of a list.
Input
[45, 12, 89, 3, 67]
Output
Min: 3 Max: 89 3 89
Approach
- Track both in one loop, or use
min()andmax().
Solution
numbers = [45, 12, 89, 3, 67]smallest = largest = numbers[0]for n in numbers: if n < smallest: smallest = n if n > largest: largest = nprint("Min:", smallest, "Max:", largest)print(min(numbers), max(numbers))Output
Min: 3 Max: 89 3 89
Line by line
Line 2
Both start at the first item, which works for negative numbers too.
Learn the concept
New to this topic? Read the lesson, then come back.