Reductions
Min, Max, and Argmax
Find the minimum, maximum, and the index of the maximum in a single pass over
a 6-element list. Two if-checks per iteration update the running extremes.
The replay shows min_val, max_val, and max_idx updating only when a new
extreme is found.
By hand
With NumPy
a.min() and a.max() return the extreme values; a.argmax() returns the
integer index of the first occurrence of the maximum. The snapshot shows the
input array followed by all three results on one line.
naive.py
values = [3, 7, 2, 9, 1, 5]
min_val = values[0]
max_val = values[0]
max_idx = 0
for i in range(len(values)):
if values[i] < min_val:
min_val = values[i]
if values[i] > max_val:
max_val = values[i]
max_idx = i
print('RESULT:', (min_val, max_val, max_idx))
library.py
import numpy as np
values = [3, 7, 2, 9, 1, 5]
a = np.array(values)
mn = int(a.min())
mx = int(a.max())
idx = int(a.argmax())
print('shape:', a.shape)
print('dtype:', a.dtype)
print('values:', a.tolist())
print('min:', mn, 'max:', mx, 'argmax:', idx)
print('RESULT:', (mn, mx, idx))
shape: (6,)
dtype: int64
values: [3, 7, 2, 9, 1, 5]
min: 1 max: 9 argmax: 3
RESULT: (1, 9, 3)
Implementation notes
argmaxreturns the index of the first maximum. If the maximum value appears more than once,argmaxreturns the lowest index — the same behaviour as the hand-written loop here, which only updatesmax_idxon a strict>comparison.a.argmin()works the same way for the minimum.- All three —
min,max,argmax— are reductions: they collapse the array to a scalar (or an index). Called without anaxisargument they operate over the entire array. int()converts the NumPy scalar return values to plain Python ints forRESULT, avoiding repr differences across NumPy versions.- Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.