Chapter 3 · Junior Developer

Built-ins: len, max, min, sum, sorted

Python ships with built-in functions for the things you'd otherwise write a loop for. Reach for these before hand-rolling:

  • len(x) — how many items (list length, string length, dict key count).
  • sum(nums) — adds up a sequence of numbers.
  • max(x) / min(x) — the largest / smallest item.
  • sorted(x) — returns a new sorted list, smallest first.

sorted(x, reverse=True) sorts largest-first. The key= argument controls *what to sort by*: pass a function applied to each item, and items sort by its result — sorted(words, key=len) orders by length, not alphabetically. max/min take a key= too.

Mind the difference between sorted() and list.sort(): sorted(x) leaves x untouched and gives back a new list; x.sort() reorders x *in place* and returns None. Use sorted() when you want a copy (or are sorting something that isn't a list); use .sort() when you genuinely want to mutate the list and don't need the original order.

Syntax

len([1, 2, 3])               # 3
sum([1, 2, 3])               # 6
max([1, 9, 4]) / min(...)    # 9 / 1
sorted([3, 1, 2])            # [1, 2, 3]  (new list)
sorted(x, reverse=True)      # largest first
sorted(words, key=len)       # sort by a computed value

x.sort()   # sorts x IN PLACE, returns None

Worked examples

Crunching a list of numbers

scores = [70, 55, 90, 80]
print(len(scores))    # 4
print(sum(scores))    # 295
print(max(scores))    # 90
print(min(scores))    # 55
print(sorted(scores, reverse=True))   # [90, 80, 70, 55]

key= changes what you sort/compare by

words = ["bbb", "a", "cc"]
print(sorted(words, key=len))   # ['a', 'cc', 'bbb']  (by length)
print(max(words, key=len))      # 'bbb'  (longest, not "largest")

sorted() returns a copy; .sort() mutates and returns None

nums = [3, 1, 2]
print(sorted(nums))   # [1, 2, 3]  (new list)
print(nums)           # [3, 1, 2]  (original untouched)

print(nums.sort())    # None  (.sort() returns nothing!)
print(nums)           # [1, 2, 3]  (nums itself changed)

Common mistakes & gotchas

x = x.sort() loses your list

.sort() mutates in place and returns None, so x = x.sort() sets x to None and throws the sorted list away. Either call x.sort() on its own line, or use x = sorted(x).

max() / min() / sum() on an empty sequence

max([]) and min([]) raise ValueError. sum([]) is fine — it's 0. If a list might be empty, guard it or give max/min a default= argument: max([], default=0).

sum() doesn't add strings

sum(['a', 'b']) raises TypeErrorsum is for numbers. To join strings use ''.join(['a', 'b']) instead.

Why it matters

These built-ins are faster to write, faster to read, and faster to run than the equivalent hand-written loop — they're implemented in C under the hood. Knowing they exist (and the `key=` trick) is the difference between five lines of loop and one clear expression that any Python developer reads at a glance.