Code Snippets
/

Combinations and Permutations

Combinations and Permutations

When the problem reads 'pick K of N' or 'order all N', the right reflex in Python is `itertools.combinations` or `itertools.permutations`. Both are lazy iterators, so they enumerate huge search spaces without materializing them. This entry walks combinations, permutations, and `combinations_with_replacement`, plus when each is the right tool.

Python
Easy
3 snippets
py-itertools
py-generators
iterators
py-standard-library

235 views

2

from itertools import combinations

team = ['ana', 'ben', 'cleo', 'dax']

# All 2-person pairs (order does not matter, no repeats).
pairs = list(combinations(team, 2))
print(pairs)
# [('ana', 'ben'), ('ana', 'cleo'), ('ana', 'dax'),
#  ('ben', 'cleo'), ('ben', 'dax'), ('cleo', 'dax')]

# Count: C(4, 2) = 6
print(len(pairs))  # 6

# Works on any iterable, output is sorted by input position.
print(list(combinations('abcd', 3)))
# [('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd')]

combinations(iterable, r) yields every r-length tuple of items in input order, with no repeats and no equivalent reorderings. The output count equals the binomial coefficient C(n, r), and the order matches the input order, so combinations of a sorted input is itself sorted. Reach for it whenever the question is 'how many ways to pick r things' and order does not matter (committee selection, edge enumeration in a graph, choosing K elements for a subset-sum check). The iterator is lazy: stopping the loop early avoids enumerating the rest.