Artificial Corner

Artificial Corner

Share this post

Artificial Corner
Artificial Corner
AI & Python #26: A Super-Fast Way to Loop in Python
Copy link
Facebook
Email
Notes
More
AI & Python 🐍

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

The PyCoach's avatar
The PyCoach
Oct 02, 2024
∙ Paid
5

Share this post

Artificial Corner
Artificial Corner
AI & Python #26: A Super-Fast Way to Loop in Python
Copy link
Facebook
Email
Notes
More
Share
Image via Shutterstock

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!

This post is for paid subscribers

Already a paid subscriber? Sign in
© 2025 Frank Andrade
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture

Share

Copy link
Facebook
Email
Notes
More