Python nested loop

Nested for loop

Python allows us to include any number of for loops inside a specific for loop.

A loop inside a loop (a nested loop) is essential in the programming languages for writing the codes for complicated problems. The "inside loop" will be performed once for every iteration of the "outside loop". A last note on loop nesting is that you can place all types of loops inside some other type of loop. So, for example, we can write it in different ways, like a for loop inside a while loop, or a while loop inside a for loop, and while loop inside a while loop, or a for loop inside a for a loop.

The two types of nested loops are mentioned below:

  • Nested for loops: A Nested for loops can be beneficial for repeating through items within the lists. In a list composed of lists, when we apply just one for loop, the program will output every inside list as an item.
  • Nested while loops: Unlike in for loop, the while loop does not have an already compiled iterable sequence. While loop continues performing the code until the expression goes right and evaluates to true. So, a developer has to keep in mind to refresh the iterating variable/expression, or else the loop will enter infinite execution mode.


web = ["website 1", "website 2"] knowledge = ["knowledge2life 1", "knowledge2life 2"] for x in web: for y in knowledge: print(x, y)


website 1 knowledge2life 1
website 1 knowledge2life 2
website 2 knowledge2life 1
website 2 knowledge2life 2