itertools: Combinatorics
Generate permutations, combinations, and cartesian products.
itertools: Combinatorics is a free Python Academy lesson on CoddyKit. This is lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, and your progress syncs across the web and the CoddyKit app. The Python Academy course includes 4 lessons in total.
Combinatorics Overview
itertools provides four combinatoric functions: product, permutations, combinations, and combinations_with_replacement.
import itertools
# All orderings of 2 items from ABC
print(list(itertools.permutations("ABC", 2)))
# [(A,B),(A,C),(B,A),(B,C),(C,A),(C,B)]product()
product(*iterables, repeat=1) computes the Cartesian product — equivalent to nested for-loops.
import itertools
print(list(itertools.product([1,2], ["a","b"])))
# [(1,"a"),(1,"b"),(2,"a"),(2,"b")]
# repeat=2 pairs each element with itself
print(list(itertools.product(range(2), repeat=2)))
# [(0,0),(0,1),(1,0),(1,1)]permutations()
permutations(it, r) yields all r-length ordered arrangements. Total: P(n,r) = n!/(n-r)!.
import itertools
result = list(itertools.permutations([1,2,3], 2))
print(result)
# [(1,2),(1,3),(2,1),(2,3),(3,1),(3,2)]
print(len(result)) # 6combinations()
combinations(it, r) yields r-length unordered selections without repetition. Total: C(n,r) = n!/(r!(n-r)!).
import itertools
result = list(itertools.combinations([1,2,3,4], 2))
print(result)
# [(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)]
print(len(result)) # 6combinations_with_replacement()
combinations_with_replacement(it, r) allows an element to appear more than once in a combination.
import itertools
result = list(itertools.combinations_with_replacement("AB", 2))
print(result)
# [(A,A),(A,B),(B,B)]Counting Without Materialising
Use math.perm, math.comb, or the len() shortcut (works for finite results) instead of generating all elements just to count them.
import math
print(math.perm(10, 3)) # 720
print(math.comb(10, 3)) # 120Password/Key Generation
Combinatorics iterators are useful for generating candidate keys or test cases without loading everything into memory.
import itertools, string
chars = string.ascii_lowercase
# All 2-char lowercase combos:
for combo in itertools.combinations(chars, 2):
pass # process without materialisingGrid Coordinates with product
Use product(range(rows), range(cols)) to iterate over a 2D grid without nested loops.
import itertools
for row, col in itertools.product(range(3), range(3)):
print(f"({row},{col})", end=" ")Testing All Subsets
Generate all subsets of a list by iterating combinations for each length from 0 to n.
import itertools
items = [1, 2, 3]
all_subsets = []
for r in range(len(items)+1):
all_subsets.extend(itertools.combinations(items, r))
print(all_subsets)Deduplicating with combinations
Use combinations to compare each pair of elements exactly once, avoiding duplicate (a,b) and (b,a) comparisons.
import itertools
words = ["apple","apricot","banana","blueberry"]
for a, b in itertools.combinations(words, 2):
if a[0] == b[0]:
print(f"Same letter: {a}, {b}")Performance Considerations
Combinatoric sequences grow very quickly. permutations(range(12)) produces 479 million results. Always use generators and only materialise what you need.
import itertools, math
n = 12
print(f"P(12,12) = {math.factorial(n):,}") # 479,001,600
# Never: list(itertools.permutations(range(12)))
# Instead: iterate lazily and break earlyQuick Check
Which itertools function produces all unordered pairs (without repetition) from a collection?
Recap
Use product for Cartesian products, permutations for ordered arrangements, combinations for unordered subsets, and combinations_with_replacement when elements can repeat. Always process combinatoric iterators lazily.
Learn Python with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 76
- Lessons
- 320
Frequently Asked Questions
Is the “itertools: Combinatorics” lesson free?
Yes — the full text of “itertools: Combinatorics” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO. The Python Academy course includes 4 lessons in total.
What will I learn in “itertools: Combinatorics”?
Generate permutations, combinations, and cartesian products. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.
How long does the “itertools: Combinatorics” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- itertools: Infinite and Finite Iterators
- itertools: Combinatorics
- functools: partial and reduce
- functools: lru_cache and cached_property