Danrex Danrex - 1 month ago 4
Python Question

What is a nested for loop?

I am running through some examples of 'nested for loops' and the below code is given as an example. But isn't this technically a for loop?

xLimits = range(getWidth(pic))
for x in xLimits:
pixel = getPixelAt(pic, x, 0)
setColor(pixel, green)


Wouldn't a nested look something like this?

for x in xLimits:
for y in yLimits:
code
code
code


Can someone either agree or disagree with me?

I know this probably doesn't matter but if I am not looking at this the right way I would like to know why.

Answer

A nested loop (of any kind) is a loop within a loop. It's important to realize that the inner loop will be re-run for every iteration of the outer loop.

For example:

for i in xrange(3):
    for j in xrange(2):
        print 'i={0} j={1}'.format(i,j)

Output:

i=0 j=0    
i=0 j=1
i=1 j=0    <-- inner loop restarts
i=1 j=1
i=2 j=0    <-- inner loop restarts
i=2 j=1

So your understanding is totally correct. The first example is not a nested loop, while the second example is.

You could possibly consider calling a function with a for loop, from within a for loop, a "nested for loop", although I would never call it that:

def foo(r):
    for i in r:
        do_something()

for x in xrange(20):
    foo( xrange(x) )
Comments