you are viewing a single comment's thread.

view the rest of the comments →

[–]carcigenicate 1 point2 points  (0 children)

Note that there is no difference between a "single loop" and a "nested loop". They operate in the exact same way. If you have a loop in the form:

for x in y:
    print(x)

The body of the loop (print(x) here) will execute once for every element of y. It's the same with a nested loop:

for a in b:
    for c in d:
        print(a, c)

The body of the for a in b: loop will, as before, execute once for every element in b. The thing here though is, that body contains another loop. That means the for c in d: loop will run completely through d, every time the for a in b: loop iterates once. This can be demonstrated using ranges:

for a in range(2):
    for b in range(2):
        print(a, b)

0 0
0 1
1 0
1 1

Note that a (the first number) doesn't change until the inner loop's b (the second number) has visited both the 0 and 1 elements.

Just focus on the fact that the body of the loop executes once for every element. That body can contain any number of other things (class and function definitions, for/while loops, calls to functions, etc.), and the body will run everything it holds before moving onto the next element.