Lists and Records
Min and Max Scan
Find the smallest and largest values in a list in a single pass. Seeding the running bounds from the first element avoids sentinel values; the trace shows exactly when each bound tightens.
By hand
Seed lo and hi from values[0] so no sentinel (0, float('inf')) is
needed. Then scan the rest: lower the floor when a new minimum appears, raise
the ceiling when a new maximum appears.
naive.py
values = [5, 2, 8, 1, 9, 3, 7, 4]
lo = values[0]
hi = values[0]
for v in values[1:]:
if v < lo:
lo = v
if v > hi:
hi = v
print('RESULT:', (lo, hi))
The Pythonic way
The built-ins min and max each walk the list once internally in C.
Two calls over eight values is negligible, and the intent is unambiguous.
library.py
values = [5, 2, 8, 1, 9, 3, 7, 4]
lo = min(values)
hi = max(values)
print('RESULT:', (lo, hi))
RESULT: (1, 9)
Implementation notes
- Seeding from
values[0]is correct for any non-empty list of any comparable type; a sentinel like0orfloat('inf')would require assumptions about the data range. - In this run
lotightens twice (5→2→1) andhirises twice (5→8→9); both progressions are visible in the trace.