Nested Loops

In this lesson, we will look at nested loops in Python. A nested loop is a loop inside another loop. It is often used when working with multiple arrays or nested arrays.

Example: We want to print all possible pairs of numbers from two lists:

numbers1 = [1, 2]
numbers2 = [3, 4]
for number1 in numbers1:
    for number2 in numbers2:
        print(number1, number2)
# Output
# 1 3
# 1 4
# 2 3
# 2 4

In this example, we go through all the numbers in the numbers1 list and for each number in this list, we go through all the numbers in the numbers2 list. For each combination of numbers, we print the pair.

Instructions

Use a for loop to go through cities, and a nested for loop to go through activities and print each pair of values.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

7/8

Nested Loops | Start Coder