5 of 6
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
items = ["sword", "shield", "potion"] for i in range(len(items)): for j in range(___): print(f"{items[i]} + {items[j]}")
If j starts at 0, you'd get repeated pairs like "shield + sword" after already printing "sword + shield". Starting j later avoids this.
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)):
i = 0: j goes 1, 2 → sword+shield, sword+potioni = 1: j goes 2 → shield+potioni = 2: j has nothing left → done3 items = 3 unique pairs!
Try it with a longer list and count the total number of pairs:
items = ["sword", "shield", "potion", "bow", "staff"] # How many unique pairs?
items = ["sword", "shield", "potion"] for i in range(len(items)): for j in range(i + 1, len(items)): print(f"{items[i]} + {items[j]}")
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