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.
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].
Finding list boundaries is essential for scaling data features, filtering outliers, and determining dataset ranges.
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]
Python iterates through the list in O(N) time to determine the lowest and highest values without modifying or sorting the original list.
min([]) or max([]) on an empty list raises a ValueError: min() arg is an empty sequence. Always check if not nums: return [].Use min() and max() for fast list extrema retrieval. Next, let's check if a string is empty!
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.
`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.
`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.