Python 3.13: List Comprehension vs. For Loop Benchmarks
ملخص
Pixel shares a Python 3.13.5 benchmark comparing 14 ways to process one million integers. List comprehensions beat a basic for loop by about 10%, while map with a lambda was slower; the results show why the loop body and interpreter optimizations matter when choosing Python performance techniques.
DEV Community
List Comprehension vs for Loop in Python 3.13: I Timed 14 Versions, the Loop Body Decides
"Use a list comprehension, it's faster" is one of the first Python performance tips people learn. It's true, but on a current Python the gap is smaller than most people expect, and in some cases it disappears completely. I timed the same work written in different ways on Python 3.13.5 over a list of 1,000,000 integers. Each number below is the best of 5 repeats of 5 runs each, using timeit, on one Linux machine. Your absolute numbers will be different. The ratios between them are what matter. The setup import timeit
setup = "data = list(range(1_000_000))"
loop = """
out = []
for x in data:
out.append(x * 2)
"""
comp = "[x * 2 for x in data]"
for name, stmt in [("for + append", loop), ("list comprehension", comp)]:
t = min(timeit.repeat(stmt, setup=setup, number=5, repeat=5)) / 5
print(f"{name:20s} {t * 1000:6.1f} ms")
Result 1: a trivial body (x * 2) Version Time for loop + out.append(x * 2) 24.3 ms for loop with ap = out.append cached 26.3 ms [x * 2 for x in data] 21.8 ms list(map(lambda x: x * 2, data)) 38.1 ms The comprehension wins, but by about 10%, not 2x. Two things stand out: Caching out.append in a local no longer helps. That trick was real on old versions. On 3.13 it was slightly slower in my runs, because the interpreter already specializes the attribute lookup. map + lambda was the slowest option. Every element pays for a Python function call. map is only fast when you pass it a built-in like str or int. Why the comprehension is faster at all Look at the bytecode. Using dis on both versions (filtered to the interesting instructions): for loop: comprehension:
BUILD_LIST BUILD_LIST
FOR_ITER FOR_ITER
LOAD_ATTR append BINARY_OP *
BINARY_OP * LIST_APPEND
CALL
The loop does an attribute lookup plus a method call for every element. The comprehension uses one dedicated LIST_APPEND instruction. That is the whole difference. It is a fixed cost per element, so it only matters when the rest of the loop body is cheap. Result 2: make the body do real work and the gap disappears Body for + append comprehension x * 2 24.3 ms 21.8 ms filter: if x % 3 == 0 26.5 ms 25.9 ms call a Python function f(x) 38.6 ms 34.0 ms f-string f"id-{x:06d}" 145.3 ms 150.5 ms With the f-string body, the comprehension was actually a little slower in this run. That's just noise. The formatting takes about 6x longer than the loop overhead, so the loop style stops mattering. The rule: loop style matters when the body is one cheap operation. Once the body formats strings, calls functions, touches the network or hits a database, the time is in the body, so optimize that. Result 3: the bigger wins are not "comprehension vs loop" Code Time [x for x in data] 6.9 ms list(data) 3.0 ms sum([x * 2 for x in data]) 24.2 ms sum(x * 2 for x in data) 20.7 ms If you're only copying, don't write a comprehension. list(data) (or data.copy()) was more than 2x faster because it never runs a Python-level loop. If you only need a total, you don't need the list. In this run the generator expression was faster and it doesn't build a million-element list in memory first. Don't assume generators are always faster. Measure it on your own data. The memory saving is real either way. So which one should you write? Use a comprehension when you're building a list from a simple expression or filter. It's shorter, it's slightly faster, and it's the style most Python developers expect. Use a for loop when the body has several steps, needs try/except, or logs or breaks early. A three-line comprehension with nested conditions is harder to read, and as Result 2 shows, you gain almost nothing. Skip the loop entirely when there's a built-in for it: list(), sum(), any(), max(), "".join(), or vectorized NumPy/pandas for numeric data. Measure with timeit on your own Python version before rewriting working code for speed. Old benchmarks from Python 3.6-era blog posts don't predict 3.11+. Reproduce it Everything above is timeit.repeat...

Powered by Readybot.io