← Back to Nested Loops
🀝

Matching Pairs

5 of 6

Exercise 4: Matching Pairs

Given a list of items, print all unique pairs (no repeats, no pairing with itself).

items = ["sword", "shield", "potion"]

Expected output:

sword + shield
sword + potion
shield + potion

Starter Code

items = ["sword", "shield", "potion"] for i in range(len(items)): for j in range(___): print(f"{items[i]} + {items[j]}")

Hints

Hint 1 β€” Why not start j at 0?

If j starts at 0, you'd get repeated pairs like "shield + sword" after already printing "sword + shield". Starting j later avoids this.

Hint 2 β€” Where should j start?

Start the inner loop at i + 1. This means j is always after i, so you never repeat a pair or pair something with itself.

for j in range(i + 1, len(items)):
Hint 3 β€” Walk through it
  • When i = 0: j goes 1, 2 β†’ sword+shield, sword+potion
  • When i = 1: j goes 2 β†’ shield+potion
  • When i = 2: j has nothing left β†’ done

3 items = 3 unique pairs!


Bonus Challenge

Try it with a longer list and count the total number of pairs:

items = ["sword", "shield", "potion", "bow", "staff"] # How many unique pairs?

Solution

Show Solution
items = ["sword", "shield", "potion"] for i in range(len(items)): for j in range(i + 1, len(items)): print(f"{items[i]} + {items[j]}")
Show Bonus Solution
items = ["sword", "shield", "potion", "bow", "staff"] count = 0 for i in range(len(items)): for j in range(i + 1, len(items)): print(f"{items[i]} + {items[j]}") count += 1 print(f"\nTotal unique pairs: {count}") # 5 items β†’ 10 pairs
πŸ’»

Try it yourself

Code: Matching Pairs

Loading Python runtime…
Python …
Loading...
Output
Click "Run" to execute your code...
ℹ️ About this Python environment

βœ… Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect

βœ… Functions, classes, recursion, print()

❌ No file system, subprocess, OS access, or network requests

❌ No pip install (all supported modules are pre-loaded)

⏱️ 5 second execution time limit