The Fastest Way to Loop in Python: Using Built‑in Functions and Formulas Instead of While/For Loops
This article benchmarks Python while and for loops, shows that for loops are faster due to fewer operations, demonstrates how built‑in functions like sum and direct arithmetic formulas can achieve orders‑of‑magnitude speedups, and concludes that the quickest way to "loop" in Python is to avoid loops altogether.
It is well known that Python is not a high‑performance language and that loops are generally time‑consuming; repeating a simple operation many times multiplies the execution time.
The two common loop keywords while and for have different runtimes. The following benchmark code measures their performance:
<code>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\t\t', timeit.timeit(while_loop, number=1))
print('for loop\t\t', timeit.timeit(for_loop, number=1))
if __name__ == '__main__':
main()
# => while loop 4.718853999860585
# => for loop 3.211570399813354</code>The result shows that the for loop is about 1.5 seconds faster because the while loop performs an extra boundary check and an explicit increment on each iteration.
To highlight the impact of these extra operations, two additional functions add unnecessary checks and increments to a for loop:
<code>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 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 s
def main():
print('while loop\t\t', timeit.timeit(while_loop, number=1))
print('for loop\t\t', timeit.timeit(for_loop, number=1))
print('for loop with increment\t\t', timeit.timeit(for_loop_with_inc, number=1))
print('for loop with test\t\t', timeit.timeit(for_loop_with_test, number=1))
if __name__ == '__main__':
main()
# => while loop 4.718853999860585
# => for loop 3.211570399813354
# => for loop with increment 4.602369500091299
# => for loop with test 4.18337869993411</code>These measurements confirm that the added boundary check and increment noticeably degrade the for loop’s speed.
Because Python’s interpreter and many built‑in functions are implemented in C, they run much faster than pure Python code. Replacing the explicit loops with the built‑in sum function yields a dramatic speedup:
<code>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 sum_range(n=100_000_000):
return sum(range(n))
def main():
print('while loop\t\t', timeit.timeit(while_loop, number=1))
print('for loop\t\t', timeit.timeit(for_loop, number=1))
print('sum range\t\t', timeit.timeit(sum_range, number=1))
if __name__ == '__main__':
main()
# => while loop 4.718853999860585
# => for loop 3.211570399813354
# => sum range 0.8658821999561042</code>The built‑in sum executes in C and is therefore orders of magnitude faster than the pure‑Python loops.
Even faster is to replace the loop entirely with the arithmetic formula for the sum of the first n integers, which can be expressed in a single Python statement:
<code>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 sum_range(n=100_000_000):
return sum(range(n))
def math_sum(n=100_000_000):
return (n * (n - 1)) // 2
def main():
print('while loop\t\t', timeit.timeit(while_loop, number=1))
print('for loop\t\t', timeit.timeit(for_loop, number=1))
print('sum range\t\t', timeit.timeit(sum_range, number=1))
print('math sum\t\t', timeit.timeit(math_sum, number=1))
if __name__ == '__main__':
main()
# => while loop 4.718853999860585
# => for loop 3.211570399813354
# => sum range 0.8658821999561042
# => math sum 2.400018274784088e-06</code>The arithmetic formula completes in microseconds, demonstrating that the fastest way to "loop" in Python is to avoid looping altogether and use built‑in functions or direct mathematical expressions.
Original article: https://www.starky.ltd/2021/11/23/the-fastest-way-to-loop-in-python
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.