Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

Why does a nested loop print more pairs than I expected?

Quick answer

In a nested loop, the inner loop runs all the way through for each item visited by the outer loop. So lists with 2 and 3 items produce 2 × 3 = 6 pairs, not 2. If you want only items at matching positions, use zip(first, second) instead; it pairs items in order and stops when the shorter input runs out. [S1]

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

I have two lists and put one for loop inside another. I expected one pair per position, but I got several more lines. Why?

Geez

Because the inner loop starts over for every item in the outer loop. The outer loop does not advance until the inner loop has finished its full pass. That means the code makes every combination of one item from the first list and one item from the second—not matches by position. [S1]

For example, assuming these lists:

colors = ["red", "blue"]
shapes = ["circle", "square", "triangle"]

for color in colors:
    for shape in shapes:
        print(color, shape)

The output is:

red circle
red square
red triangle
blue circle
blue square
blue triangle

There are 2 choices for color and 3 choices for shape, so the total is 2 × 3 = 6 pairs. The first color is used with all three shapes before the loop moves to the second color. [S1]

Follow-up question

How can I work out the number of lines before I run the code? Is it always the product of the list lengths?

Geez

For this simple pattern—one inner loop that completes for every outer-loop item—the number of times the inner body runs is the outer iterable’s item count multiplied by the inner iterable’s item count. For lists of lengths 2 and 3, that is 6. [S1]

You can count the passes: red gets 3 turns through the inner loop; then blue gets 3 more. That gives 3 + 3 = 6. With 4 outer items and 5 inner items, the same pattern would run 20 times. These counts assume the loop bodies do not change what is iterated over and that there are no conditions or early exits that skip or stop iterations. If your code includes those features, inspect them too; simple multiplication may not describe its printed lines.

Follow-up question

I only want the first color with the first shape, then the second color with the second shape. What should I change?

Geez

Use zip to iterate over corresponding items together, rather than nesting one loop inside another:

colors = ["red", "blue"]
shapes = ["circle", "square", "triangle"]

for color, shape in zip(colors, shapes):
    print(color, shape)

This pairs items in order and stops as soon as the shorter input is exhausted. [S1] With these lists, it prints red circle and blue square; triangle has no matching color, so it is not included. If you need every item from both lists to be paired, check that the input lengths are what you expect before using zip.

Follow-up question

Can you give me a quick way to decide which pattern I need when I read or write a loop?

Geez

Ask what one output line represents. If each item from list A should be combined with every item from list B, use the nested loop. If one line should combine item 1 with item 1, item 2 with item 2, and so on, use zip.

A small planning note can make the choice clear:

Desired output: every color with every shape
Pattern: nested loops
Expected pairs: 2 × 3 = 6

Desired output: corresponding positions only
Pattern: zip(colors, shapes)
Expected pairs: 2 (the shorter list's length)

Before running the code, write down the two input lengths and a few expected output lines. Then compare that prediction with the actual output. This helps distinguish an intentional all-combinations loop from one that should pair items by position.

A practical checklist

  • Write down what one printed line is supposed to pair.

  • Count the items in each input iterable.

  • For all combinations, multiply the two counts and use nested loops.

  • For matching positions, use zip(first, second).

  • If using zip, check whether stopping at the shorter input is acceptable.

  • Compare the first few predicted pairs with the program's output.

A few more useful answers

Why does the first item from the outer list appear repeatedly?

The inner loop runs through all of its items before the outer loop advances. Each outer item therefore appears once with every inner item.

What happens with `zip` when the lists have different lengths?

zip stops when the shortest input iterable is exhausted, so unmatched items in a longer list are not paired. [S1]

Does every nested loop print the product of the list lengths?

That count applies to the simple case where the inner loop completes for each outer item and the body runs on every iteration. Conditions, early exits, or changes to the iterables can affect the number of printed lines.

Sources

References used for this guide.

  1. [S1] Python Tutorial: For statements and iteration
    docs.python.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work