Find the Minimum and Maximum Numbers in a List
Quick Overview
`min()` and `max()` each walk the list once, so calling both is two passes over the same data. On an empty list they raise `ValueError` unless a `default=` is supplied.
Deep Dive
1. The Challenge: Min and Max Extrema
Create a function find_min_max(nums) that takes a list of numbers and returns a list containing both the smallest and largest numbers in that order: [min, max].
2. Why It Matters
Finding list boundaries is essential for scaling data features, filtering outliers, and determining dataset ranges.
3. The Python Solution
Use Python's built-in min() and max() functions:
def find_min_max(nums):
return [min(nums), max(nums)]
# Testing our function
print(find_min_max([1, 2, 3, 4, 5])) # Output: [1, 5]
print(find_min_max([2334454, 5])) # Output: [5, 2334454]
print(find_min_max([1])) # Output: [1, 1]
print(find_min_max([-10, 0, 50, 20])) # Output: [-10, 50]
4. How Built-in min() and max() Work
Python iterates through the list in O(N) time to determine the lowest and highest values without modifying or sorting the original list.
5. Common Mistakes
- ValueError on Empty Lists: Calling
min([])ormax([])on an empty list raises aValueError: min() arg is an empty sequence. Always checkif not nums: return [].
6. Next Steps
Use min() and max() for fast list extrema retrieval. Next, let's check if a string is empty!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
Convert Minutes into Seconds
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
Calculate the Area of a Triangle
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.