0Pricing
Python Academy · Lesson

itertools: Combinatorics

Generate permutations, combinations, and cartesian products.

itertools: Combinatorics is a free Python Academy lesson on CoddyKit — 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, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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))  # 6

combinations()

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))  # 6

combinations_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))   # 120

Password/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 materialising

Grid 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 early

Quick 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.

Frequently asked questions

Is the “itertools: Combinatorics” lesson free?

Yes — the full text of “itertools: Combinatorics” is free to read here on the web, and the Python Academy course includes 4 lessons in total. 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.

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; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

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

  1. itertools: Infinite and Finite Iterators
  2. itertools: Combinatorics
  3. functools: partial and reduce
  4. functools: lru_cache and cached_property
← Back to Python Academy