Skip to content
Python: Count unordered selections with math.comb

Python: Count unordered selections with math.comb

November 26, 2026

math.comb(n, k) counts ways to choose k items from n without repetition, ignoring order. It returns the count directly, so a report that only needs a total does not need to create every selection.

Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.

Run the example

Save this as combination_count.py in an empty working directory:

from math import comb

print("Choose 6 from 60:", comb(60, 6))
print("Choose none:", comb(60, 0))
print("More than available:", comb(3, 4))
print("Complement agrees:", comb(60, 6) == comb(60, 54))
try:
    comb(5, -1)
except ValueError:
    print("Negative selection: rejected")

Run it without -O so any assertions remain enabled:

python3 combination_count.py

Captured output:

Choose 6 from 60: 50063860
Choose none: 1
More than available: 0
Complement agrees: True
Negative selection: rejected

Choosing six items from sixty gives 50,063,860 combinations. Choosing none has one result: the empty selection. Choosing more items than exist returns zero, while a negative selection size raises ValueError.

Limits and cleanup

The inputs must be integers, and both must be nonnegative. If your application considers k > n an input error, validate that rule explicitly; the function returns zero for it. This example checks counts, not the time or memory needed to enumerate combinations.

After testing, remove the example script from its working directory:

rm -- combination_count.py

Reference

Python 3.12 documentation

Acknowledgements

This post was created with assistance from AI.

Last updated on