Sub topic 6
Idioms that cost less: join, comprehensions, and built-ins
This chapter assumes you can read a cProfile report and have already used timeit (earlier chapters in this tutorial). It also assumes you know the basics of lists, dicts, sets, and generators. The idioms here are small, local changes. They usually give a constant-factor speedup, not a change in complexity. Fix the algorithm and data structure first, then apply these to hot spots the profiler has actually shown you.
The working model: why idioms differ in cost
CPython runs bytecode in an interpreter loop. Each bytecode instruction has overhead, and a Python-level for loop pays that overhead on every iteration. Built-in functions and methods such as sum, str.join, sorted, and min are written in C. They run their inner loop without going back through the interpreter for each element.
Three costs explain most idiom advice:
- Interpreter overhead per iteration. Fewer bytecode instructions per element means less time.
- Repeated copying. Some operations create a new object each time. Strings are the classic case.
- Repeated lookups. Looking up
result.appendor a global name on every iteration costs a little each time.
Building strings with `str.join`
Strings are immutable. The expression slow += part creates a new string that holds the old content plus part. Done naively in a loop, this copies the growing string over and over, so the work grows roughly with the square of the final length.
parts = [str(i) for i in range(1_000)]
slow = ""
for part in parts:
slow += part
fast = "".join(parts)
assert slow == fast"".join(parts) first computes the total size, allocates once, and copies each piece once. That is linear in the total length.
CPython sometimes optimizes += on a string when nothing else references it. This is an implementation detail. Other interpreters such as PyPy don't guarantee it, and it breaks if another reference exists. Treat join as the portable and predictable choice.
The separator goes before .join, and the items must all be strings:
numbers = [1, 2, 3]
try:
",".join(numbers)
except TypeError as exc:
print("TypeError:", exc)
print(",".join(str(n) for n in numbers))
print(",".join(map(str, numbers)))The TypeError is the most common beginner mistake with join. Convert items with str first, as the last two lines show.
For a small, fixed number of pieces (two or three), + or an f-string is fine and often clearer. join matters when the number of pieces grows with your data.
Comprehensions versus explicit loops
A list comprehension builds the list inside a dedicated bytecode path. It avoids looking up and calling result.append as a Python-level method call on each iteration. Compare three ways of doubling a list:
import timeit
setup = "data = list(range(100_000))"
loop_stmt = """
result = []
for x in data:
result.append(x * 2)
"""
comp_stmt = "result = [x * 2 for x in data]"
map_stmt = "result = list(map(lambda x: x * 2, data))"
for name, stmt in [("loop", loop_stmt), ("comprehension", comp_stmt), ("map+lambda", map_stmt)]:
t = min(timeit.repeat(stmt, setup=setup, number=20, repeat=5))
print(f"{name:14s} {t:.4f}s")On a typical CPython build, the comprehension is the fastest, often by 20 to 40 percent over the explicit loop. map with a lambda is usually not faster than the comprehension, because each element still calls a Python function. map wins mainly when you pass a built-in or C-implemented function, such as map(str, numbers). Exact numbers vary with the Python version and machine, so run it yourself. The code takes the minimum of several repeats, which is the least noisy estimate.
The gain from a comprehension is a constant factor. A comprehension that does expensive work per item, such as a database call, is still slow. Comprehensions are also not a reason to cram logic into one line. If the body needs several statements, a plain loop is clearer, and the profile will tell you whether it matters.
Generators when you don't need the list
A generator expression uses the same syntax in parentheses. It produces items one at a time and never builds the full list.
import sys
as_list = [n * n for n in range(1_000_000)]
as_gen = (n * n for n in range(1_000_000))
print("list: ", sys.getsizeof(as_list), "bytes (container only)")
print("generator:", sys.getsizeof(as_gen), "bytes")
print(sum(n * n for n in range(1_000_000)))sys.getsizeof on the list counts only the list's own pointer array, not the integer objects it holds, so the true gap is larger than printed. Use a generator when you consume the result once, for example when feeding sum, any, or join. Use a list when you need to iterate more than once, index into it, or take its len. A generator is exhausted after one pass, and a second loop over it silently yields nothing.
Generators are not always faster. For small inputs, the list comprehension often wins on time, because generators pay for suspending and resuming on each item. The main win is memory.
Let built-ins do the loop
Built-ins that work over iterables run their loop in C. Prefer them over hand-written equivalents.
| Task | Hand-written loop | Built-in |
|---|---|---|
| Total of numbers | `total += x` in a loop | `sum(data)` |
| Largest value | compare in a loop | `max(data)` |
| Any item matches | loop with `break` | `any(pred(x) for x in data)` |
| All items match | loop with early return | `all(pred(x) for x in data)` |
| Sorted copy | manual sort | `sorted(data, key=...)` |
| Count occurrences | dict increment | `collections.Counter(data)` |
import timeit
setup = "data = list(range(100_000))"
manual = """
total = 0
for x in data:
total += x
"""
builtin = "total = sum(data)"
print("manual :", min(timeit.repeat(manual, setup=setup, number=50, repeat=5)))
print("sum() :", min(timeit.repeat(builtin, setup=setup, number=50, repeat=5)))sum over a list of ints is typically several times faster than the manual loop.
Short-circuiting with `any` and `all`
any and all stop as soon as the answer is known. With a generator expression, the work stops at the first match. With a list comprehension, every item is evaluated first.
def is_big(n):
print("checking", n)
return n > 2
data = [1, 2, 3, 4, 5]
print(any(is_big(n) for n in data)) # stops after checking 3
print(any([is_big(n) for n in data])) # checks all five firstThe first call prints three "checking" lines. The second prints five. Passing a list comprehension to any is a common mistake that throws away the short-circuit.
Sorting with `key`
sorted(data, key=func) calls func once per element, not once per comparison. Prefer key over the old cmp-style approach. For simple lookups, operator.itemgetter and operator.attrgetter are C-implemented and cheaper than an equivalent lambda:
from operator import itemgetter
rows = [("ana", 31), ("bo", 25), ("cy", 40)]
print(sorted(rows, key=itemgetter(1)))
print(max(rows, key=itemgetter(1)))Smaller lookup and call costs
These savings are real but small. Use them only inside a loop the profiler has flagged.
- Local names are faster than globals. Inside a hot function, copy a global or attribute to a local once:
append = result.append. Python 3.11 and later made much of this cheaper, so the gain is smaller than it used to be. - Avoid repeated work inside the loop. Compute
len(data), a compiled regex, or a constant outside the loop. - Use
dict.get,setdefault, ordefaultdictinstead of aif key in dcheck followed by a lookup. This does one lookup, not two. - Use
inon sets and dicts for membership. That is a data-structure choice and was covered in the previous chapter. - Function calls are not free. A tiny function called a million times adds measurable overhead. Inline it only when a profile shows
tottimeconcentrated there, because readability usually matters more.
Common errors
- Using
+=on strings in a loop where the number of pieces grows with the input. Usejoin. - Passing non-strings to
join. Convert first withstrormap(str, ...). - Using a list comprehension inside
anyorall. This defeats short-circuiting. Use a generator expression. - Reusing an exhausted generator. A second pass produces nothing and raises no error.
- Using a comprehension for side effects, such as
[print(x) for x in data]. It builds a throwaway list. Use a plain loop. - Trusting one timing run. Use
timeit.repeatand take the minimum, or compare the profile before and after.
Exercise
A function builds a report with report = "" and then report += line + "\n" for each of 200,000 lines, and the profiler shows it dominates the runtime. Rewrite the construction with join, and say why the original gets slower as the input grows.
Show answer
Collect the lines and join once: report = "\n".join(lines) + "\n" (or "".join(line + "\n" for line in lines)). Strings are immutable, so each += can copy the whole string built so far. Total copying grows roughly with the square of the final length, while join sizes the result once and copies each piece once, so its cost is linear.
Exercise
You need to know whether any of 1,000,000 records has status == "error". Which is better, any([r.status == "error" for r in records]) or any(r.status == "error" for r in records), and why?
Show answer
The second. The generator expression lets any stop at the first match, so it may examine only a few records. The list comprehension builds a list of a million booleans first, which costs time and memory before any runs at all.