Nested Loop

Nested Loop

Nested Loop

Nested Loop

A nested loop is a loop that is contained within another loop. Nested loops are used when you need to iterate over a sequence of items multiple times. The syntax for a nested loop is simply to include one loop inside the other.

Here’s an example of a nested loop that iterates over a list of numbers and multiplies each number by 2 for each letter in a string:

				
					numbers = [1, 2, 3]
letters = "abc"

for number in numbers:
    for letter in letters:
        print(number * 2, letter)
				
			

In this example, the outer loop iterates over each number in the list “numbers”. For each number, the inner loop iterates over each letter in the string “letters”. For each combination of number and letter, the code block inside the nested loop is executed, which simply prints the number multiplied by 2 and the letter.

The output of this code would be:

				
					2 a
2 b
2 c
4 a
4 b
4 c
6 a
6 b
6 c
				
			

As you can see, the inner loop is executed 3 times for each iteration of the outer loop, resulting in a total of 9 iterations of the nested loop. Nested loops can be very useful when you need to perform a task that requires iterating over multiple sequences at the same time.

Join To Get Our Newsletter
Spread the love