Danrex Danrex - 1 year ago 58
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:

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 Source

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)


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:

for x in xrange(20):
    foo( xrange(x) )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download