The block of a loop can contain any statements. That includes another loop. A loop inside another loop is called a nested loop. The one on the outside is the outer loop; the one inside it is the inner loop.
forhourinrange(1,3):
forminuteinrange(3):
print(f"hour {hour}, minute {minute}")print("--- the hour is over ---")
Output
hour 1, minute 0
hour 1, minute 1
hour 1, minute 2
--- the hour is over ---
hour 2, minute 0
hour 2, minute 1
hour 2, minute 2
--- the hour is over ---
The whole inner loop is one of the statements in the outer loop's block. So for each value of hour, the inner loop starts from the beginning and runs all the way through.
Tracing it
Step
hour
minute
What happens
1
1
—
outer loop takes its first value
2
1
0
inner loop starts; prints
3
1
1
prints
4
1
2
prints; the inner loop is finished
5
1
2
prints the "over" line
6
2
—
outer loop takes its next value
7
2
0
inner loop starts again from 0; prints
8
2
1
prints
9
2
2
prints; the inner loop is finished
10
2
2
prints the "over" line; the outer loop is finished
The important rows are 2 and 7. Every time the outer loop begins a new pass, the inner loop is started afresh. The inner variable changes quickly, like the minute hand. The outer variable changes slowly, like the hour hand.
Indentation shows who owns what
for hour in range(1, 3): ◄── outer loop
for minute in range(3): ◄── inner loop
print(f"hour {hour}, minute {minute}") ◄── INNER block: runs 2 x 3 = 6 times
print("--- the hour is over ---") ◄── OUTER block only: runs 2 times
print("done") ◄── after both loops: runs once
Indentation
Belongs to
Runs
8 spaces
the inner loop
once for every combination
4 spaces
the outer loop only
once per outer pass
0 spaces
neither
once, afterwards
Moving a line in or out by one level changes how many times it runs. In nested loops, the indentation rule from Chapter 11 matters more than ever.
The passes multiply
The outer loop makes 2 passes. For each one, the inner loop makes 3. The innermost line runs 2 × 3 = 6 times. In general:
Inner passes in total = (outer passes) × (inner passes per outer pass).
A 10-by-10 nested loop runs its inner block 100 times. A 1000-by-1000 one runs it a million times. Section 15.9 comes back to why that matters.
Quick check
How many times is print called here? for x in range(4): then (inner) for y in range(5): then (innermost) print(x, y). What is the first line printed, and the last?
Show the answer
Answer: 20 times (4 × 5). The first line is 0 0 and the last is 3 4.
The deepest line runs for every combination, the line with 4 spaces runs once per day, and the line with no indentation runs once at the end.
15.2 Staying on the same line
Nested loops are often used to print grids, and that needs control over where each line ends. You met end= briefly in Chapter 13. Here is what you need for this chapter. (The full story of print is in → Chapter 16.)
print(x) shows x and then moves to a new line.
print(x, end="") shows x and stays on the same line, adding nothing.
print(x, end=" ") shows x followed by a space, and stays on the line.
print() with nothing in the brackets just ends the current line.
Read it as three steps that repeat: (1) the inner loop prints five stars side by side; (2) the bare print() ends that line; (3) the outer loop moves on to the next row.
The print() is in the outer block (four spaces). Indent it into the inner block, and every star lands on its own line. Leave it out, and all fifteen stars run together on one line. This single line is the most common thing to get wrong.
Showing the coordinates
Print the two loop variables in place of the star and you can see exactly how they move:
Along each line, row stays fixed and column counts up. This picture, a grid of (row, column) positions, is the one to keep in your head for every nested loop.
A multiplication grid
A table has rows and columns, so it is a nested loop. rjust from Chapter 9 pads each number to the same width so the columns line up:
After the inner loop has printed one row, a bare print() in the outer block ends that line.
Write code
Seat labels. Ask for the number of rows, then for the number of seats in each row. Print one line for each row. On a line, show every seat as the row number, a dash and the seat number, such as 2-3, with one space between seats. Rows and seats are counted from 1.
A space at the end of a line does not matter.
With the replies 2 then 3, the program prints the lines below. Your program must print exactly these lines.
Example run
1-1 1-2 1-3
2-1 2-2 2-3
Output
The outer loop goes through the rows and the inner loop through the seats. Both start at 1, so use range(1, rows + 1) and range(1, seats + 1).
Print each label with end=" ". After the inner loop, end the line with print().
rows=int(input("Rows: "))seats=int(input("Seats in each row: "))forrowinrange(1,rows+1):
forseatinrange(1,seats+1):
print(f"{row}-{seat}",end=" ")print()
The inner block uses both loop variables, as in the coordinates example of section 15.3. The bare print() belongs to the outer block.
Multiple choice
In the star rectangle of this section, the bare print() is moved one level deeper, into the inner block. What do you see?
In the inner block, a line runs once for every star.
A bare print() ends the current line. Think about what happens when that follows every single star.
The answer is: Every star on its own line
Inside the inner block, print() ends the line after each star. It must be in the outer block to end the line once per row.
15.4 When the inner loop depends on the outer loop
In a rectangle, every row has the same length. For other shapes, the length of each row depends on which row it is. That means the inner loop's range uses the outer loop's variable.
Row 1 counts down from 1, row 2 from 2 and row 3 from 3. Nothing is printed between the numbers.
It prints
1
21
321
The inner range is worked out again for each row with the current value of row, so every row counts down from its own number.
Write code
Stairs on the right. Ask for a size. Print a triangle of * with that many rows, pushed to the right: row 1 has one star, row 2 has two stars, and so on, and every row is filled with spaces on the left so that all rows end in the same column. For size 3, the rows hold 2 spaces and 1 star, then 1 space and 2 stars, then 3 stars. Use nested loops.
With the reply 4, the program prints the lines below. Your program must print exactly these lines.
Example run
*
**
***
****
Output
Each row needs two things: spaces first, then stars. That means two inner loops, one after the other, as in the pyramid.
Row row needs size - row spaces and row stars. End the line after the second inner loop.
For each row, the first inner loop prints the spaces, the second prints the # characters, and print() ends the line.
15.5 Every pair
Many problems are about pairs: every combination of a shirt with a pair of trousers, every pair of players who must meet, every pair of numbers that add up to a target.
All combinations of two different lists
When the two things come from different collections, a plain nested loop gives every combination:
range(i + 1, len(players)) means "only the players that come after player i". Each pair appears exactly once, and nobody is paired with themselves.
Inner loop starts at
You get
Count for 4 items
0
every ordered pair, including with itself
16
i
each pair once, including with itself
10
i + 1
each pair of different items, once
6
The pattern for i in range(n) with for j in range(i + 1, n) is one to memorise. It appears whenever you compare items of a collection with each other: finding duplicates, finding the closest two values, checking for clashes in a timetable.
Searching for a combination
Which pairs of whole numbers from 1 to 10 multiply to give 24?
Starting the inner loop at x avoids listing both 3 x 8 and 8 x 3. Trying every combination like this is called a brute-force search. It is not clever, but it is simple and it is correct, and for small ranges it is instant.
Practice 15.5
Fill in the blank
Fill in the blank so that each pair of different letters is printed once.
Starting at i + 1 means j is always greater than i: no letter is paired with itself, and no pair appears in both orders.
Write code
Pairs with a sum. Ask for a target number. Find every pair of whole numbers x and y from 1 to 9 with x smaller than y and x + y equal to the target. Print each pair on its own line in the form 1 + 9, with the smallest x first. Then print a last line: Pairs:, a space and the number of pairs found.
With the reply 10, the program prints the lines below. Your program must print exactly these lines.
Example run
1 + 9
2 + 8
3 + 7
4 + 6
Pairs: 4
Output
Try every combination with two loops. Start the inner loop at x + 1, so that y is always larger than x.
Inside the if, print the pair and add 1 to a counter. Print the counter after both loops.
This is a brute-force search over every pair. Starting y at x + 1 lists each pair once, with the smaller number first.
Fix the bug
This should print each pair of numbers from 1 to 10 that multiply to give 18, once, with the smaller number first. It prints every pair in both orders. Fix it.
The program prints the lines below. Your program must print exactly these lines.
Example run
2 x 9
3 x 6
Output
The inner loop tries values of y that are smaller than x. Those give the second copy of each pair.
Change where the inner range starts, so that y is never smaller than x.
When column reaches 3, break ends the inner loop. The outer loop knows nothing about it. It prints its "ended" line and carries on with the next row, where the inner loop starts again and breaks again.
That is often exactly what you want. But sometimes you want to stop everything as soon as you have found an answer. Suppose you are searching a grid for the first pair whose product is 12:
The inner break leaves the inner loop. Straight afterwards, the outer block checks the flag and breaks as well. It is a little wordy, but anyone can read it.
Way 2: put the loops in a function
Inside a function, the return statement ends the whole function at once, however deeply nested the loops are. This is usually the cleanest solution, and you will be able to use it after → Chapter 19.
Way 3: the loop's else
Python loops have a feature made for this situation. It needs a section of its own.
break leaves only the loop it is directly inside. Which loop is that here?
In each of the 3 outer passes, the inner loop adds 1 one time and then breaks. After that, the outer block adds 10.
The answer is: 33
break ends the inner loop only, so all 3 outer passes run. Each one adds 1 in the inner loop and 10 in the outer block.
15.7 The else of a loop
A for or while loop can be followed by an else block. It has nothing to do with the else of an if, and its name is widely agreed to be confusing. Here is what it means:
A loop's else block runs when the loop finishes normally. It is skipped if the loop was ended by break.
Many Python programmers read it in their heads as "no break".
forninrange(3):
print(n)else:
print("The loop finished without a break.")
Output
0
1
2
The loop finished without a break.
forninrange(3):
print(n)ifn==1:
breakelse:
print("The loop finished without a break.")print("After the loop")
Output
0
1
After the loop
for item in sequence:
if found_it:
break ───────────────┐ leaving by break skips the else
else: │
(runs only if the loop │
used up all its items) │
next statement ◄─────────────┘
Notice the indentation: the else lines up with the for, not with the if inside the loop.
What it is for: searching
Almost every real use is a search: "look through these for something. If you find it, stop. If you get to the end without finding it, do this other thing."
Chapter 14 tested for a prime number with a flag:
n=91is_prime=Truefordivisorinrange(2,n):
ifn%divisor==0:
is_prime=Falsebreakifis_prime:
print(n,"is prime")else:
print(n,"is not prime")
Output
91 is not prime
With a loop else, the flag disappears:
n=97fordivisorinrange(2,n):
ifn%divisor==0:
print(n,"is not prime: it divides by",divisor)breakelse:
print(n,"is prime")
Output
97 is prime
Read it as: try every divisor. If one works, report it and stop. If the loop gets through all of them with no break, the number is prime.
Another search, for a character in a string:
text=input("Text: ")forchintext:
ifch.isdigit():
print("First digit found:",ch)breakelse:
print("There are no digits in the text.")
Output
Text: hello world
There are no digits in the text.
Three details
An empty loop counts as finishing normally. If the sequence has no items, the block never runs, no break happens, and the else runs. For the prime test with n = 2, range(2, 2) is empty, so 2 is prime is printed, which is correct.
It works with while too. The else runs when the condition becomes false, and is skipped after a break.
Without a break in the loop, the else is pointless. It would always run, so the code might as well be written after the loop with no else.
Quick check
What does this print? for ch in "abc": with the block if ch == "z": break, followed by else: print("no z")
Show the answer
Answer:no z. The loop looked at every character, never reached the break, and so finished normally.
Leaving two loops with else
Now for the third way promised in section 15.6. The outer block can use the inner loop's else to decide whether to keep going:
forxinrange(1,6):
foryinrange(1,6):
ifx*y==12:
print("Found:",x,y)breakelse:
continue# the inner loop was NOT broken: go on to the next xbreak# the inner loop WAS broken: leave the outer loop too
Output
Found: 3 4
Follow the two cases:
The inner loop finishes without finding anything. Its else runs, and continue jumps to the next pass of the outer loop, skipping the final break.
The inner loop breaks. Its else is skipped, so the next statement is the final break, which ends the outer loop.
This is a well-known Python idiom, and you should be able to read it when you meet it. Many programmers find the flag clearer, and a function with return clearest of all. Use whichever you can explain easily.
The loop breaks at the first divisor. The else belongs to the for and runs only when no divisor was found.
Fix the bug
This should print the first digit of the reply and stop looking. It should print No digit only when the reply has no digit. Now it prints every digit, and No digit after every reply. Fix it.
With the reply x7y9, the program prints the lines below. Your program must print exactly these lines.
Example run
Digit found: 7
Output
A loop else runs whenever the loop ends with no break. Is there a break in this loop?
Leave the loop as soon as a digit is found: add break inside the if, after the print.
When the inner loop was not broken, continue moves to the next x and skips the last break. When it was broken, the else is skipped and the last break ends the outer loop.
15.8 Mixing for and while
Any loop can be nested in any other. Choose each one by the rule from Chapter 14: "for each" or "until".
A for inside a while
A menu that keeps going until the user leaves is a while. Each action it performs may contain a for:
whileTrue:
n=int(input("Table for which number (0 to stop)? "))ifn==0:
breakforiinrange(1,4):
print(f" {n} x {i} = {n*i}")print("Goodbye.")
Output
Table for which number (0 to stop)? 3
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
Table for which number (0 to stop)? 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
Table for which number (0 to stop)? 0
Goodbye.
The break here sits directly in the while block, not inside the for, so it ends the while.
A while inside a for
For each number from 20 to 24, count how many times it can be halved before it becomes odd. The outer loop is "for each number"; the inner loop is "until it is odd":
forninrange(20,25):
value=nhalvings=0whilevalue%2==0:
value//=2halvings+=1print(n,"can be halved",halvings,"times")
Output
20 can be halved 2 times
21 can be halved 0 times
22 can be halved 1 times
23 can be halved 0 times
24 can be halved 3 times
Two things here are worth copying:
halvings = 0 is inside the outer loop but before the inner one. It must be reset for each new number. An accumulator belongs just outside the loop that fills it. Put it above the outer loop and the counts would run together. Put it inside the inner loop and it would reset on every halving.
The work is done on a copy, value. Changing n itself would not upset the for loop (Chapter 14 showed that), but the last line needs the original number for its message.
Primes up to a limit
Nested loops and the loop else together list every prime below 30. The outer loop picks a candidate; the inner loop searches for a divisor:
The inner loop, with its else, is the complete prime test from section 15.7. The outer loop simply runs that test for each candidate. Building a bigger program by wrapping a loop around something that already works for one case is a very good way to work.
For each start, the while loop halves value with whole-number division until it is 1.
steps is set to 0 again for every new start. For 5: 5 becomes 2, then 1.
It prints
3 1
4 2
5 2
The outer for picks each number, and the inner while runs until the value reaches 1. steps is reset just before the loop that fills it.
Write code
Digit sums. Ask for a first whole number, then for a last whole number. For every number from the first to the last, both included, print one line: the number, one space, and the sum of its digits. For 98 the line is 98 17. The numbers are never negative.
With the replies 17 then 21, the program prints the lines below. Your program must print exactly these lines.
Example run
17 8
18 9
19 10
20 2
21 3
Output
The outer loop goes through the numbers. The inner loop goes through the digits of one number: loop over str(number), or use a while loop with % 10 and // 10.
Set the sum to 0 inside the outer loop, before the inner loop, so that every number starts from zero.
The outer loop means "for each number" and the inner loop collects that number's digits. The sum is reset just before the inner loop.
15.9 How much work is a nested loop?
Because the passes multiply, nested loops grow quickly. Suppose both loops run n times:
n
One loop
Two nested loops
Three nested loops
10
10
100
1 000
100
100
10 000
1 000 000
1 000
1 000
1 000 000
1 000 000 000
10 000
10 000
100 000 000
1 000 000 000 000
Chapter 13 said Python manages some tens of millions of simple passes per second. So two nested loops over 1 000 items take a moment. Over 10 000 items they take several seconds. Three nested loops over 1 000 items would take around a minute, and over 10 000 items, many hours.
Making the input ten times bigger makes a double loop take a hundred times longer. Programmers say such a loop takes time proportional to n squared.
Three habits keep nested loops under control:
Do not repeat work in the inner loop. Anything that does not change in the inner loop should be calculated once, outside it.
Stop as soon as you can. A break at the first answer can save most of the work.
Shrink the inner range. The prime test does not need divisors all the way up to n. If n has a divisor at all, it has one no bigger than its square root, so range(2, int(n ** 0.5) + 1) is enough. For a number near a million, that is about a thousand checks instead of a million.
Later you will meet data structures that replace an entire inner loop with a single instant lookup → Chapter 37. For now, the lesson is simply to notice when you are nesting, and to ask how big the numbers will get.
Practice 15.9
Multiple choice
A program with two nested loops over the same items needs about 1 second for 2 000 items. About how long does it need for 20 000 items?
The number of inner passes is the number of items times the number of items.
The input is ten times bigger. Both loops become ten times longer, and the passes multiply.
The answer is: 100 seconds
Ten times the items means ten times ten, a hundred times the work, for two nested loops.
15.10 Common mistakes
The mistake
What you see
The fix
The line-ending print() inside the inner loop
Every item on its own line
Dedent it to the outer block
No line-ending print() at all
The whole grid on one long line
Add print() after the inner loop
The same variable for both loops
Confusing results; the outer value is overwritten
Use different names: row and column, i and j
A counter reset in the wrong place
Totals that keep growing, or that are always tiny
Reset it just before the loop that fills it
Expecting break to leave both loops
The outer loop carries on
A flag, a function with return, or the loop else
A loop else indented under the if
The "not found" branch runs on every pass
Line the else up with for or while
A loop else when the loop has no break
The else always runs
Remove the else
The inner range starts at 0 when pairing
Every pair twice, and items paired with themselves
Start the inner loop at i + 1
The outer loop variable used in the inner range by mistake, or forgotten
The wrong shape
Make a row-by-row table first
Unnecessary nesting
A program that slows to a crawl on larger inputs
Ask whether the inner loop is really needed
Practice 15.10
Fix the bug
For each row of a 3-by-3 grid, this should count the positions where row + column is even. The correct counts are 2, 1 and 2. Now every count is too small. Fix it.
The program prints the lines below. Your program must print exactly these lines.
Example run
Row 1 has 2
Row 2 has 1
Row 3 has 2
Output
Where is count set to zero? How many times does that line run for one row?
A counter is reset just before the loop that fills it. Move count = 0 out of the inner loop, but keep it inside the outer loop.
Inside the inner loop, the counter is wiped on every pass. It belongs in the outer block, just before the inner loop.
15.11 Choosing the right loop: a summary
Three chapters of loops come down to this:
You want to...
Use
do something for each character, item or number in a known range
for
repeat a fixed number of times
for _ in range(n)
repeat until something happens, without knowing how long
while
repeat until the user decides to stop
while True with break
work with rows and columns, or every pair
nested loops
search, and act on "not found"
a loop with break and else
stop early
break
skip the rest of this pass
continue
15.12 Putting it together
15.13 How nested loops work inside Python
+ Practice
Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.
Questions
Check yourself
In a nested loop, how many times does the inner loop run from start to finish?
Show the answer
Once, completely, for every single pass of the outer loop.
Check yourself
An outer loop runs 6 times and its inner loop runs 4 times per pass. How many times does the innermost line run?
Show the answer
24 times (6 × 4).
Check yourself
In a grid-printing loop, where does the bare print() go, and what does it do?
Show the answer
In the outer block, after the inner loop. It ends the current line, so the next row starts on a new line.
Check yourself
What does the inner range(row) do in a triangle pattern?
Show the answer
It makes the inner loop run row times, so each row has as many items as its row number.
Check yourself
Why does for j in range(i + 1, n) avoid pairing an item with itself and avoid listing a pair twice?
Show the answer
j only takes values greater thani. So j is never equal to i, and of the two orders of any pair, only the one with the smaller index first is ever produced.
Check yourself
Which loop does a break inside the inner loop end?
Show the answer
Only the inner loop. The outer loop continues with its next pass.
Check yourself
When does a loop's else block run? When is it skipped?
Show the answer
It runs when the loop ends normally: the sequence is used up, or the while condition becomes false. It is skipped when the loop is left by break.
Check yourself
Why is a loop else pointless when the loop contains no break?
Show the answer
Without a break the loop always ends normally, so the else always runs. The code could just be placed after the loop.
Check yourself
In section 15.8, why is halvings = 0 placed inside the outer loop and not before it?
Show the answer
It must start again from zero for each number. Before the outer loop it would be set only once, and the counts for different numbers would add together.
Check yourself
A double loop takes 2 seconds for 5 000 items. Roughly how long will it take for 50 000 items?
Show the answer
Ten times the items means about a hundred times the work: roughly 200 seconds.
Handshakes. Five people named by the letters VWXYZ each shake hands once with every other person. Print every handshake and the total number.
Print every handshake on one line in the form V-W, with one space between handshakes, in the order the loops make them. Then print a second line: Handshakes:, a space and the total.
The program prints the lines below. Your program must print exactly these lines.
First repeated letter. Ask for a word and print the first letter that appears more than once, or a message if no letter repeats. Use a loop else.
Go through the word from the left and stop at the first letter that appears again later in the word. Print First repeated letter: and the letter, or print No letter repeats. The tests use lower-case words.
With the reply programming, the program prints the lines below. Your program must print exactly these lines.
Example run
First repeated letter: r
Output
For each position i, search the part of the word that comes after it for the same letter. An inner loop from i + 1 does that, and so does in with a slice.
break as soon as a repeat is found. The else of the outer loop then prints the other message.
word=input("A word: ").lower()foriinrange(len(word)):
ifword[i]inword[i+1:]:
print("First repeated letter:",word[i])breakelse:
print("No letter repeats.")
For each position, the inner check looks at the rest of the word. The loop else handles "nothing repeated".
word=input("A word: ").lower()foriinrange(len(word)):
ifword[i]inword[i+1:]:
print("First repeated letter:",word[i])breakelse:
print("No letter repeats.")
Output
A word: programming
First repeated letter: r
Here in with a slice does the work of an inner loop: it searches the rest of the word for the same letter.
Write code · Hard
Right-angled triangles. Find every set of whole numbers x, y, z with x < y < z and z at most 30 where x * x + y * y == z * z. Print each set and the total.
Print each set on its own line as three numbers with one space between them, in the order the loops find them. Then print a last line: Total:, a space and the number of sets.
The program prints the lines below. Your program must print exactly these lines.
This version uses string repetition for each row. Written with inner loops, each " " * k becomes for s in range(k): print(" ", end=""), as in the pyramid in section 15.4.
Write code · Hard
Perfect numbers. A perfect number equals the sum of its divisors, not counting itself: 6 = 1 + 2 + 3. Find every perfect number below 10 000.
Print the perfect numbers from the smallest to the largest. A simple program needs several seconds here, so wait for it to finish.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
6 28 496 8128
Output
Set the sum to zero inside the outer loop, before the inner loop, so that every candidate starts fresh.
an outer loop over the candidates and an inner loop adding up divisors. Divisors of n other than n itself are never bigger than n // 2, which halves the work.
Only four exist below 10 000. This program makes about 25 million inner passes, so it takes a second or two to run: a small taste of section 15.9. total = 0 sits inside the outer loop, so that each candidate starts from zero.
Chapter project: Tournament planner
Project
Plan a small tournament. Every team has a one-letter name, and every team plays every other team once. Write a program that asks for the team letters as one piece of text, such as KLMN.
First check the letters. Go through the text from the left. If a letter appears again later in the text, print Repeated letter:, a space and that letter, and print nothing else. Report only the first such letter.
If no letter is repeated, print every match on its own line in the form Match 1: K v L. The match numbers count up from 1. The matches come in this order: the first team against each later team, then the second team against each later team, and so on.
After the matches, print a last line: Matches:, a space and the number of matches.
Use nested loops for the check and for the list of matches. Remember that break leaves one loop only.
With the reply KLMN, the program prints the lines below. Your program must print exactly these lines.
Example run
Match 1: K v L
Match 2: K v M
Match 3: K v N
Match 4: L v M
Match 5: L v N
Match 6: M v N
Matches: 6
Output
Both parts compare positions: i for one team and j for a later team. The inner loop starts at i + 1, as in section 15.5.
For the check, the inner break leaves only the inner loop. Store the repeated letter in a variable that starts as an empty string, and test it in the outer block to leave the outer loop too.
After the check, an if decides: print the repeated letter, or else run the second pair of loops. Add 1 to the match counter before you print the match, so that the first match has number 1.
The program uses the i + 1 pattern two times: once as a search that must leave two loops, and once to list each pair exactly once while a counter numbers the matches.