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!
Keep reading with a 7-day free trial
Subscribe to Artificial Corner to keep reading this post and get 7 days of free access to the full post archives.