The Fastest Way to Loop in Python: Using Built‑in Functions and Math Instead of While/For Loops
This article demonstrates that in Python, plain while and for loops are significantly slower than using built‑in functions like sum or applying a direct mathematical formula, because the former execute extra Python‑level boundary checks and increments, making the latter the most efficient looping alternatives.
Python is known for its relatively low execution speed, and loops are especially time‑consuming; repeating a simple operation millions of times can cause the total runtime to grow proportionally.
The article presents a benchmark comparing a while loop and a for loop that each sum numbers from 0 to n . The for loop completes about 1.5 seconds faster than the while loop.
import timeit
def while_loop(n=100_000_000):
i = 0
s = 0
while i < n:
s += i
i += 1
return s
def for_loop(n=100_000_000):
s = 0
for i in range(n):
s += i
return s
def main():
print('while loop', timeit.timeit(while_loop, number=1))
print('for loop', timeit.timeit(for_loop, number=1))
if __name__ == '__main__':
main()The speed gap stems from the while loop performing two extra Python‑level operations each iteration: an explicit boundary check ( while i < n ) and an increment ( i += 1 ), both written in pure Python.
In contrast, a for loop relies on the C‑implemented iterator protocol, so it does not execute those extra Python statements, resulting in noticeably better performance when the iteration count is large.
Adding unnecessary checks and increments to a for loop (e.g., manually incrementing i or inserting an if i < n: pass ) reproduces the slowdown observed with the while loop, confirming that extra Python code hurts speed.
def for_loop_with_inc(n=100_000_000):
s = 0
for i in range(n):
s += i
i += 1
return s
def for_loop_with_test(n=100_000_000):
s = 0
for i in range(n):
if i < n:
pass
s += i
return sUsing Python’s built‑in sum function, which is implemented in C, yields a dramatic speed improvement: the same summation completes in under one second, far faster than either loop.
def sum_range(n=100_000_000):
return sum(range(n))Even faster is applying a direct mathematical formula (Gauss’ trick) to compute the sum in constant time, reducing execution time to microseconds.
def math_sum(n=100_000_000):
return (n * (n - 1)) // 2The final conclusion is that the quickest way to “loop” in Python is to avoid explicit loops altogether—prefer built‑in functions or closed‑form formulas to minimize pure‑Python overhead.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.