Sub topic 6
Idioms that cost less: join, comprehensions, and built-ins
This chapter assumes you can write Python loops and functions, know lists, dicts, and sets, and have already profiled a script with cProfile. Idioms are small rewrites. They rarely beat a better algorithm, so apply them only to code the profiler has shown to be hot.
Why idioms matter
Each Python bytecode instruction has overhead. A loop that runs a million times pays that overhead a million times. Built-in functions and comprehensions move more of the loop into C code, so the interpreter does less work per item.
Build strings with join
Strings are immutable. Each += in a loop may create a new string and copy the old contents into it. CPython sometimes optimizes this case, but you cannot rely on that across implementations or in every situation. str.join computes the final size once and copies each piece once.
parts = [str(i) for i in range(1_000)]
slow = ""
for part in parts:
slow += part
fast = "".join(parts)
assert slow == fastjoin takes an iterable of strings and the separator is the string you call it on. Use ", ".join(names) for comma-separated output.
Prefer comprehensions to append loops
A list comprehension avoids looking up and calling list.append on every iteration. It is usually faster, and it states the intent in one line.
import timeit
def with_loop(n):
result = []
for i in range(n):
result.append(i * 2)
return result
def with_comprehension(n):
return [i * 2 for i in range(n)]
print(timeit.timeit(lambda: with_loop(10_000), number=200))
print(timeit.timeit(lambda: with_comprehension(10_000), number=200))The exact ratio depends on your Python version and machine, so run it yourself.
If you only need to consume values once, use a generator expression. It produces items lazily and never builds the full list.
total = sum(i * i for i in range(1_000_000))
print(total)Use built-ins
Functions such as sum, min, max, any, all, sorted, and len run their loops in C. Replace hand-written versions with them.
numbers = [3, 8, 1, 9, 4]
# Hand-written loop
largest = numbers[0]
for n in numbers:
if n > largest:
largest = n
# Built-in
assert largest == max(numbers)any and all also stop at the first decisive item, so any(x > 100 for x in numbers) can finish early.
Common mistakes
- Using a list comprehension when you only need a sum.
sum([x for x in data])builds a list for nothing. Drop the brackets. - Joining non-strings.
"".join([1, 2])raisesTypeError. Convert first withstr. - Comprehensions with side effects.
[print(x) for x in data]builds a list ofNone. Use a plainforloop. - Rewriting cold code. An idiom that saves microseconds in a function that runs once adds risk and no benefit.
Workflow
- Profile and find the hot function.
- Check the algorithm and data structure first.
- Apply one idiom change at a time.
- Time the function before and after.
- Keep the change only if the gain is real and the code stays readable.
Exercise
A function builds a report with report += line + "\n" for each of 50,000 lines. Rewrite it using str.join, and say why the new version is safer for performance.
Show answer
Use report = "\n".join(lines) + "\n" (or "".join(line + "\n" for line in lines)). Strings are immutable, so repeated += can copy the growing string many times. join calculates the total size once and copies each piece once, so the cost grows linearly with the data.
Exercise
You find total = sum([price * qty for price, qty in items]) in a hot path. What is wasteful about it, and what is the fix?
Show answer
The square brackets build a full temporary list that sum reads once and discards. Use a generator expression: sum(price * qty for price, qty in items). This avoids the list allocation and its memory use.