Nested loops in Python are a type of loop that is used to iterate over multiple sequences in a single iteration. It is called a nested loop because it contains one or more inner loops inside an outer loop.
The Basic structure of Nested Loops in Python is as Follows:
for variable1 in sequence1: for variable2 in sequence2: # code block to be executed
Here, sequence1 and sequence2 are any iterable objects such as lists, tuples, or strings. The outer loop iterates over the elements of sequence1 and assigns them to the variable variable1. Then, for each iteration of the outer loop, the inner loop iterates over the elements of sequence2 and assigns them to the variable variable2. The code block inside the inner loop is executed for each combination of variables from both sequences.
A nested for loop can also have more than two levels, in which case the structure would look like this:
for variable1 in sequence1: for variable2 in sequence2: for variable3 in sequence3: # code block to be executed
Here is an example of a nested for loop that prints the multiplication table of the numbers from 1 to 10:
for i in range(1, 11): for j in range(1, 11): print(i, "x", j, "=", i*j)
The outer loop iterates over the numbers from 1 to 10 using the range() function and assigns them to the variable i. The inner loop also iterates over the numbers from 1 to 10 using the range() function and assigns them to the variable j. For each combination of i and j, the code block inside the inner loop prints the multiplication of i and j.
Nested for loops are often used when working with multi-dimensional arrays or matrices, as well as when working with multiple lists or other iterable objects. They can also be used in conjunction with other types of loops such as while loops and if-else statements to create more complex control flow structures.
It’s important to be mindful of the number of iterations that nested for loops can make, as the number of iterations increases exponentially with each level of nesting. This can lead to a large amount of computation time for large data sets.