Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 397
Danrex Avatar asked Jun 19 '26 19:06

Danrex


1 Answers

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) )
like image 162
Jonathon Reinhart Avatar answered Jun 22 '26 08:06

Jonathon Reinhart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!