Ritik Jangir
Ritik Jangir

Reputation: 157

Is it a bad practice to use 3 nested for loops?(or more!)

I've always wondered, what the best practices are to write code like a professional.

for i in a[:]:
    print("i in for loop = %s" %i)
    print("\n")
    for x in range(2):
        for y in range(2):
            print(y)
print("A mask for this image can be of row * column config. 1x1, 1x2, 1x3, 2x1,...,3x3:")

Something tells me that my approach is never preferred.

Upvotes: 0

Views: 5792

Answers (2)

nissim abehcera
nissim abehcera

Reputation: 831

It's a practice to avoid as much as possible because the number of nested loops and efficiency are directly connected.

If you have 1 nested loop complexity of algorithm is on average O(n)2 and 2 nested loops complexity increase to O(n)3. If you have n elements in your data structure, say n=1000 O(n)2 is equivalent to 1000*1000 crossing over elements in you data structure and O(n)3 1000*1000*1000 .Global complexity of algorithm it's depend also on eventual functions inside nested loops and can increase the final complexity.

Upvotes: 0

Philipp F
Philipp F

Reputation: 427

In general, the more nesting you have, the harder it is to read the code. In cases where you just want to do something for every x and y in some range, you can use itertools.product:

import itertools
for x, y in itertools.product(range(2), range(2)):
    # Do something for every x, y
    print(x, y)

This way, you save one nesting, and it is still readable. This would even scale for an additional variable, e.g., z.

Upvotes: 1

Related Questions