Performance Basics
Before optimizing anything, measure — Python's built-in timeit
module times a piece of code precisely.
import timeit
def using_loop():
result = []
for n in range(1000):
result.append(n * 2)
return result
def using_comprehension():
return [n * 2 for n in range(1000)]
print(timeit.timeit(using_loop, number=1000))
print(timeit.timeit(using_comprehension, number=1000))
A list comprehension is typically faster than an equivalent explicit
loop with .append(), since it's optimized internally by Python. The
general rule: optimize the specific part measured to be slow, not
whatever feels slow.