AI & Python #26: A Super-Fast Way to Loop in Python
Do you think Python is slow? Here's a fast way to loop in Python
Python is known for being a slow programming language. Although itβs a fact that Python is slower than other languages, there are some ways to speed up our Python code.
How? Simple, optimize your code.
If we write code that consumes little memory and storage, weβll not only get the job done but also make our Python code run faster.
Hereβs a fast and also a super-fast way to loop in Python.
The averageΒ loop
Say we want to sum the numbers from 1 to 100000000 (we might never do that but that big number will help me make my point).
A typical approach would be to create a variable total_sum=0
, loop through a range and increment the value of total_sum
by i
on every iteration.
import time
start = time.time()
total_sum = 0
for i in range(100000000):
total_sum += i
print(f'Sum: {total_sum}')
print(f'For loop: {time.time() - start} seconds')
This gets the job done, but it takes around 6.58 seconds.
Although that doesnβt look so slow now, itβll get slower as you add more 0s to the number inside the range.
Letβs speed this up!