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]
The question, the details, the next step.
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.
- [S1] Python Tutorial: For statements and iteration docs.python.org · Checked
