How Nested For Loop works in Python - Tutorial for beginners.

Nested "for loops" in Python- how they work?

 
A nested loop in Python is a loop inside another loop. The inner loop is executed once for each iteration of the outer loop.



Three examples with lists will explain nested for loop in Python.

----------------------------------------------

Example 1:

color : White
White Dog
White Cat
White Bear
color : Bronze
Bronze Dog
Bronze Cat
Bronze Bear
color : Black
Black Dog
Black Cat
Black Bear

Process finished with exit code 0
The first loop goes through the elements in the color list. For each color, the inner loop runs through all the elements in the animal list.
After the inner loop finishes, the outer loop moves to the next color and repeats the process.
Example 2:

color:  White
Dog
Cat
Bear
color: Bronze
Dog
Cat
Bear
color: Black
Dog
Cat
Bear

Process finished with exit code 0

 The outer for loop goes through the color list. For each element, it is printed and then the inner loop runs. When the inner loop finishes, the outer loop moves to the next element and repeats this process until the end of the list.

Example 3:

White Dog
White Cat
White Bear
Bronze Dog
Bronze Cat
Bronze Bear
Black Dog
Black Cat
Black Bear

Process finished with exit code 0

In this example, the outer loop prints a color from the list. For each color, the inner loop runs through the animal list and prints the color and the animal.
This continues until all colors have been processed.

 

Example 4:

Printing List elements side by side 



Ford Ka
Mercedes Class A
With "join method"  merged elements are printed in same line with zip function.


Comments