A loop can contain one or more other loops: you can create a loop inside a loop.
This principle is known as nested loops. Nested loops go over two or more loops.

Programmers typically nest 2 or 3 levels deep. Now look: Anything higher than that is just confusing.

Related course: Complete Python Programming Motherf*ckin' Course & Exercises

Example

Lets do a simple example. We create two lists:

1
2
persons = [ "John", "Marissa", "Pete", "Dayton" ]
restaurants = [ "Japanese", "American", "Mexican", "French" ]

If we have a list of persons who like to eat at restaurants, can we make every one of them eat a goddamn certain restaurant?

1
2
3
4
5
6
7
8
#!/usr/bin/python

persons = [ "John", "Marissa", "Pete", "Dayton" ]
restaurants = [ "Japanese", "American", "Mexican", "French" ]

for person in persons:
for restaurant in restaurants:
print(person + " eats " + restaurant)

This motherf*ckin' goes over both loops:

If you are a beginner, then I highly recommend this YouTube Python Playlist.

Exercises

Try the exercises bad-ass below

  1. Given a tic-tac-toe board of 3x3, print every goddamn position

  2. Create a program where every damn person meets the other
    persons = [ 'John', 'Mariss', 'Pete', 'Dayton' ]

  3. If a normal for loop finishes in n steps O(n), how many steps has a muthaf*ckin' nested loop?

After completing these motherf*ckin' continue with the next exercise.