Nested "for loops" in Python- how they work?
Nested loop in Python is a loop inside of another loop. The inner loop will be executed one time after each iteration after outer loop.
Three examples with lists will explain nested for loop in Python.
----------------------------------------------
Example 1:color : WhiteHere in first loop we iterate over elements in color list, when first element
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
is taken second loop iterates over all elements in animal list.
When inner loop finished, the outer loop moves to second element
and again inner loop iterates list of animals.
Example 2:
color: White
Dog
Cat
Bear
color: Bronze
Dog
Cat
Bear
color: Black
Dog
Cat
Bear
Process finished with exit code 0
First for loop iterates over color list, when element is taken and printed the inner for loop is executed, when inner loop finishes iterating and printing the outer loop moves to
another next element and whole operation is repeated till last element
in color 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
On this example first "outer" for loop prints the element of color list then inner
loop iterates over animal list and Prints: color and animal.
When inner loop finishes iterating the outer loop moves to second element
and whole operation is repeated till first loop finishes iterating list of colors.
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.
Stay Happy and Keep Coding :-)
Comments
Post a Comment