ReviseAlgo Logo

Built-in Functions

min, max, sum

Aggregate functions for finding extremes and totals

Interview: Common in interviews — custom key functions and default parameter for empty iterables

Last Updated: June 12, 2026 7 min read

min(), max(), and sum() are fundamental aggregate functions that compute the minimum, maximum, and total of iterables. They support custom key functions for complex data and a default parameter to handle empty iterables gracefully.

min() and max()

  • Iterable form: min([3, 1, 2]) — returns the smallest element
  • Multiple args: min(3, 1, 2) — same result, arguments instead of iterable
  • key parameter: min(words, key=len) — compare by function result instead of value
  • default parameter: min([], default=0) — prevents ValueError on empty iterables

sum()

  • start parameter: sum([1, 2, 3], 10) — starts at 10, result is 16
  • Empty iterable: Returns start value (default 0) — no error
  • Not for strings: sum(["a", "b"]) raises TypeError — use "".join() instead
  • Flatten lists: sum([[1,2],[3,4]], []) — flattens but O(n^2), prefer itertools.chain

nsmallest and nlargest

For finding the top-K elements, heapq.nlargest(k, iterable) is more efficient than sorted(iterable)[-k:] when K is small relative to N. It uses a heap internally for O(n log k) performance.

Empty Iterable Gotcha

min([]) and max([]) raise ValueError. Always use default or check if the iterable is non-empty first. sum([]) returns 0 without error.

Use Cases

Finding extremes in datasets: highest score, lowest price, longest string

Aggregate statistics: total revenue, average score, price range

Top-K problems: top 3 students, cheapest 5 products, most popular items

Data validation: checking values are within expected ranges

Mathematical computations: sums of squares, dot products, prefix sums

Common Mistakes

Calling min()/max() on empty iterables without default — raises ValueError

Using sorted()[-k:] for top-K when heapq.nlargest() is more efficient

Using sum() for string concatenation — use "".join() instead (much faster)

Not knowing about math.fsum() — sum() has floating-point precision issues

Forgetting that min/max return the ELEMENT, not the index — use enumerate or range for index