liveBook · Manning

Math.comb

As explained in Statistics Every Programmer Needs

math.comb is a Python math-module function that returns the number of combinations of a specified size from a given number of items.

math.comb(n, r) returns the number of ways to choose r items from n possibilities when order does not matter and replacement is not allowed. It provides a direct Python implementation of the combinations-without-replacement count. section 2.2.3

Use math.comb() when:

  • Each selection comes from n distinct possibilities. section 2.2.3
  • You select r items without replacement, so an item cannot be selected again. section 3.2.3
  • The order of the selected items does not affect the outcome. section 3.2.3

Counting five choose three

Set n = 5 and r = 3, then call math.comb(n, r). The result is 10, matching the corresponding entry in Pascal’s triangle and the factorial-based calculation. In a probability problem, these 10 selections form the numerator for getting exactly two heads in five flips; with 32 equally likely sequences, the probability is 10/32, approximately 31%. section 3.2.3 section 2.2.3

>>> n = 5
>>> r = 3

>>> combinations = (math.factorial(n) / \
>>>                 (math.factorial(r) * math.factorial(n - r)))
>>> print(f'Number of combinations without replacement: '
>>>       f'{combinations}')
Number of combinations without replacement: 10.0

>>> combinations = math.comb(n, r)
>>> print(f'Number of combinations without replacement: '
>>>       f'{combinations}')
Number of combinations without replacement: 10

Compare the factorial expression with math.comb(n, r): both count combinations without replacement, while math.comb() returns the integer result directly. section 2.2.3

How Statistics Every Programmer Needs covers it

How deep it goes
Explains arguments, counting assumptions, factorial equivalence, and worked output, but does not develop implementation internals.
Examples
Uses five coin flips, Pascal’s triangle, poker hands, and a five-item selection with three chosen items.
What it assumes
Assumes basic Python calls and elementary probability, while defining n, r, replacement, and order through examples.
What you can do after
Apply it via Python’s math module to count unordered selections and construct exact probability numerators.
How it connects
Connects combinations without replacement with factorials, Pascal’s triangle, permutations, combinations with replacement, and probability.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Statistics Every Programmer Needs. The section links point to the parts of the book it draws on.