Alternative to nesting for loops in Python

Posted by davenz on Stack Overflow See other posts from Stack Overflow or by davenz
Published on 2012-12-17T05:00:58Z Indexed on 2012/12/17 5:03 UTC
Read the original article Hit count: 234

Filed under:
|
|

I've read that one of the key beliefs of Python is that flat > nested. However, if I have several variables counting up, what is the alternative to multiple for loops? My code is for counting grid sums and goes as follows:

def horizontal():
    for x in range(20):
        for y in range(17):
            temp = grid[x][y: y + 4]
            sum = 1 
            for n in temp:
                sum += int(n)
            return sum

This seems to me like it is too heavily nested. Firstly, what is considered to many nested loops in Python ( I have certainly seen 2 nested loops before). Secondly, if this is too heavily nested, what is an alternative way to write this code?

© Stack Overflow or respective owner

Related posts about python

Related posts about for-loop