Level 1
0 / 100 XP

Nested Loops

A nested loop is a loop that is inside another loop. In other words, a loop is nested within another loop. Here's an example of a nested loop in Python:

Python
# initialize the outer loop variable i to 1 i = 1 # while the outer loop variable i is less than or equal to 3 while i <= 3: # initialize the inner loop variable j to 1 j = 1 # while the inner loop variable j is less than or equal to 3 while j <= 3: # print the value of the outer and inner loop variables print(f"i = {i}, j = {j}") # increment the inner loop variable j by 1 j = j + 1 # increment the outer loop variable i by 1 i = i +1

In this example, the outer while loop will execute 3 times, and the inner while loop will execute 3 times on each iteration of the outer loop. This means that the inner while loop will execute a total of 9 times.

Here's an example of iterating over a list of list

Python
# iterate over a list of lists list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for sublist in list_of_lists: # iterate over the elements in the current sublist for element in sublist: print(element)

Nested loops are useful for iterating over a list of lists, or for any situation where you need to loop over multiple sequences in a single block of code. By using nested loops, you can avoid writing separate loops for each sequence, which can make your code more concise and easier to read.