Google News
logo
Python Program to Nested for loop
In the following example of Python program that demonstrates how to use nested `for` loops :
Program :
# Nested for loop
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
    for y in fruits:
        print(x, y)

print("Done.")
Output :
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Done.
In the above program, we use two `for` loops to iterate over two separate lists : `adj` and `fruits`. The outer loop iterates over the adjectives in `adj`, while the inner loop iterates over the fruits in `fruits`.

Inside the nested loops, we use the `print()` function to print a combination of each adjective and fruit.

When the loops complete, the program continues to execute the `print()` statement outside the loops, which prints the message "Done."

You can use nested `for` loops to iterate over multiple lists or nested data structures. Each loop will iterate over the items in its respective data structure, and the inner loop will execute for each iteration of the outer loop.