John Hon John Hon - 7 months ago 8
Python Question

What do nested for loops actaully do?

I could understand what for loop did, but then when i saw nested for loops i got confused. I don't understand the application and also how the loop actually works. Does the outside loop execute the inside one, or does the inside activate first etc. Also, if i had them iterating over 2 lists of 4 separate strings, would this create 16 different lines of text?

Thank you

Answer

"Does the outside loop execute the inside one, or does the inside activate first etc" - the outside loop executes the inside one.

"Also, if i had them iterating over 2 lists of 4 separate strings, would this create 16 different lines of text?" - Yes - see example.

An example:

listA = ['red','blue','green','yellow']
listB = ['cat','dog','mouse','parrot']

for a in listA:
    for b in listB:
        print(a,b)

This prints:

red cat
red dog
red mouse
red parrot
blue cat
blue dog
blue mouse
blue parrot
green cat
green dog
green mouse
green parrot
yellow cat
yellow dog
yellow mouse
yellow parrot

There is an important point about for loops in Python (and many other languages): you must not alter the list (or strictly speaking the iterable) within the loop. In our example you must not alter ListA anywhere in the loop, and you must not alter either ListA or ListB in the inner loop.

"I don't understand the application" - using nested loops is not mandatory, and not every program requires them. An example application (there are many): let's say you have a list of filenames and we want to read each file in that list. The outer loop would iterate (loop-through) the list of filenames, opening each one in turn. The inner loop would be reading lines from the current file.

for filename in filelist:
    fp = open(filename)
    for line in fp:
        # Process line
    fp.close()

So if we had 10 files each of 50 lines then the # Process line would execute 500 times.

Note: purists will use with for processing files, but I don't want that to cloud the issue of using for loops.

Nested loops can get difficult to debug and understand (and you have seen) so it is often wise to place the inner loop inside a function and just call the function from inside the loop. Of course you see functions being called inside loops all the time, and you might not immediately realise that those functions could have loops of their own.

def read_file(name):
    fp = open(filename)
    for line in fp:
        # Process line
    fp.close()

for filename in filelist:
    read_file(filename)
Comments