Skip to content
Related Articles

Related Articles

Why does a nested loop perform much faster than the flattened one?

View Discussion
Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 22 Jul, 2021
View Discussion
Improve Article
Save Article

Python provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time.  

In this article, we will see why does a nested loop performs better than the flattened one. But first, let’s see what is a nested loop and what is a flattened loop.

  • Nested loops are the logical structure in computer programming and coding. In which one loop statement is inside another loop statement.


for [iter_1] in [sequence_1]:
    for [iter_2] in [sequence_2]:
          # statements of inner loop

    # statements of outer loop
  • Loops have the ability to iterate over the items of any sequence, such as a list or a string.


for [iter] in sequence:

When we run our python script, the operating system we are running on will assign a Process ID for it. It can be interrupted by system calls and its priority can be changed over time. But the system is not likely to take resources away from a process when we change memory address or values. When we run flat for loop it is assigning much fewer variables than a nested loop. So we can say that a nested loop utilizes resources more than a flat loop if they are available. 



# import module
import time
# flattened loop
def loop(n):
    for i in range(n**3):
# nested loop
def nested(n):
    for i in range(n):
        for j in range(n):
            for k in range(n):
for i in range(10, 100, 10):
    start = time.time()
    print('For flattened loop:',time.time() - start)
    start = time.time()
    print('For nested loop:',time.time() - start)


For flattened loop: 2.7894973754882812e-05
For nested loop: 4.9114227294921875e-05

For flattened loop: 0.0002155303955078125
For nested loop: 0.00024271011352539062

For flattened loop: 0.0007171630859375
For nested loop: 0.0007529258728027344

For flattened loop: 0.0016894340515136719
For nested loop: 0.0012614727020263672

For flattened loop: 0.0029077529907226562
For nested loop: 0.0022766590118408203

For flattened loop: 0.004510402679443359
For nested loop: 0.003597736358642578

For flattened loop: 0.007539272308349609
For nested loop: 0.0057599544525146484

For flattened loop: 0.01167440414428711
For nested loop: 0.008468151092529297

For flattened loop: 0.016645431518554688
For nested loop: 0.01381683349609375

We can see that the time taken by the nested loop decreases for the increasing value of n.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!