Compare a Python list comprehension with an equivalent loop, and show that the comprehension is faster.
The two versions do the same thing, and the comprehension is consistently quicker.
import time
data = range(500_000)
start = time.perf_counter()
result = []
for value in data:
result.append(value * 2)
loop_seconds = time.perf_counter() - start
start = time.perf_counter()
fast = [value * 2 for value in data]
comp_seconds = time.perf_counter() - start
print(f"loop: {loop_seconds:.4f}s")
print(f"comprehension: {comp_seconds:.4f}s")
print(len(result), len(fast))Both produce 500,000 doubled values. The comprehension is usually around twice as fast on CPython, though the exact numbers depend on your machine and Python version, so treat the output as a demonstration rather than a figure to quote.
The reason is the bytecode. A list comprehension compiles to a dedicated loop that the interpreter runs directly, while the explicit version runs a Python-level for statement whose body performs a method lookup and a method call on every iteration. The overhead of resolving items.append each time is a large part of the difference.
That said, speed is not the reason to prefer comprehensions. Readability is. The comprehension says what the code produces in one expression, whereas the loop separates the intent across three lines and leaves the reader to notice that the append is the only thing happening.
The honest caveat is that a comprehension is only clearer while it stays short. Once it needs a condition and a transformation and a nested loop, it becomes a dense line of brackets that is harder to scan than a loop with a named variable. The right rule is: comprehension when it fits on one or two lines, loop when it does not.