Why the Fastest Way to Loop in Python Is Not to Loop at All
This article compares Python's while and for loops, shows benchmark results revealing that for loops run faster due to fewer Python‑level operations, and demonstrates that using built‑in functions like sum or applying a mathematical formula can make looping dramatically faster, often eliminating the loop entirely.
It is well known that Python is not a high‑performance language and that loops are time‑consuming; repeating a simple operation millions of times multiplies the execution time.
The two common loop keywords while and for have different runtimes. A benchmark shows a for loop summing numbers from 0 to n is about 1.5 seconds faster than an equivalent 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()
# => while loop 4.718853999860585
# => for loop 3.211570399813354The speed gap comes from the extra boundary check and explicit increment that the while loop performs on each iteration, both written in pure Python, whereas the for loop relies on C‑level iteration.
Adding unnecessary checks or increments to a for loop eliminates its advantage, as shown by two additional functions that deliberately insert those operations.
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, reduces the runtime dramatically to under one second.
def sum_range(n=100_000_000):
return sum(range(n))Even faster is applying the arithmetic series formula directly, which eliminates the loop entirely and finishes in microseconds.
def math_sum(n=100_000_000):
return (n * (n - 1)) // 2Thus, the fastest way to “loop” in Python is to avoid explicit loops and use built‑in functions or mathematical formulas whenever possible.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
