HOWTO · Python
Binomial Coefficient in Python
Learn how to calculate a binomial coefficient in Python with math.comb(), SciPy, factorials, and a multiplicative product.
On this page
A binomial coefficient counts how many different groups of a chosen size can be selected from a larger set when order does not matter. Python offers a direct standard-library function, two SciPy functions, and straightforward ways to implement the formula yourself. The best choice depends on whether you need exact integer results, SciPy-specific behavior, or a calculation you can adapt.
What Is a Binomial Coefficient?
The binomial coefficient “n choose k,” written (\binom{n}{k}), is the number of ways to select k items from n distinct items without regard to order. Its formula is
[
\binom{n}{k} = \frac{n!}{k!(n-k)!}
]
where ! denotes a factorial. For example, choosing a team of 3 people from 10 gives (\binom{10}{3}=120) possible teams. Choosing Alice, Ben, and Cara is the same team regardless of the order in which their names are listed.
For the ordinary combinatorics problem, n and k are integers with n >= 0 and 0 <= k <= n. The coefficient is an exact integer. If you are instead modeling the probability of a number of successes across repeated trials, see Binomial Distribution in Python; the distribution uses binomial coefficients but answers a different question.
Use math.comb() to Calculate a Binomial Coefficient in Python
For integer combinations, math.comb(n, k) is the simplest standard-library choice. It returns an exact integer and does not require an additional package. It also handles the symmetry (\binom{n}{k}=\binom{n}{n-k}) internally, so callers can pass either side of the selection.
Run this example:
import math
print(math.comb(10, 3))
This example is provided for execution by the article runtime; no observed output is included in this draft. math.comb() expects integer inputs. For the usual nonnegative-integer problem, k must not exceed n; invalid arguments are rejected by the function. Use this method when the desired answer is the exact number of unordered selections.
Calculate Binomial Coefficients with SciPy
SciPy provides scipy.special.binom() and scipy.special.comb(), but the two functions are not interchangeable in every situation. Both require SciPy, an additional dependency that is commonly useful in scientific Python projects.
scipy.special.binom(n, k) is defined using the gamma function and supports real-valued arguments. Its result is floating point, so it is suited to generalized calculations rather than cases where exact integer arithmetic is essential. In particular, it does not impose the same integer-combination interpretation as math.comb().
scipy.special.comb(n, k, exact=False) is intended for combinatorial inputs. By default, it returns a floating-point result. Set exact=True when n and k are integers and an exact integer result is needed. This option does not make arbitrary real-valued inputs exact. Check the function’s input restrictions when handling values outside the ordinary range of integer combinations.
Choose SciPy when it is already part of the project or its broader numeric behavior is useful. For a plain integer answer with no third-party dependency, prefer math.comb().
Use math.factorial() to Implement the Formula
The defining formula can be implemented directly with math.factorial(). This makes the relationship between combinations and factorials visible, but it computes three factorial values before dividing. It is a useful teaching implementation; for routine calculations, math.comb() is more direct.
from math import factorial
def binomial(n, k):
if n < 0 or k < 0 or k > n:
raise ValueError("require n >= 0 and 0 <= k <= n")
return factorial(n) // (factorial(k) * factorial(n - k))
The function checks the ordinary combinatorics domain and uses integer division. Under those assumptions the division is exact. Factorials grow quickly, so this version constructs large intermediate integers that are not needed to represent the final coefficient. Python integers retain arbitrary precision, but that does not make the extra work preferable for large inputs.
Calculate a Binomial Coefficient with a Multiplicative Product
A product formula avoids constructing the full factorials. For valid integer inputs, use
[
\binom{n}{k}=\prod_{i=1}^{k}\frac{n-k+i}{i}.
]
Each step can use integer division exactly, because the partial result after each factor is an integer. operator.mul supplies multiplication to functools.reduce; alternatively, an explicit loop can make the update easier to follow.
import operator
from functools import reduce
def binomial_product(n, k):
if n < 0 or k < 0 or k > n:
raise ValueError("require n >= 0 and 0 <= k <= n")
k = min(k, n - k)
return reduce(
operator.mul,
(n - k + i for i in range(1, k + 1)),
1,
) // reduce(operator.mul, range(1, k + 1), 1)
This version shows the numerator and denominator products separately, but it still builds intermediate values and performs a final division. A loop that updates the result at every step can keep intermediates smaller:
def binomial_product_loop(n, k):
if n < 0 or k < 0 or k > n:
raise ValueError("require n >= 0 and 0 <= k <= n")
k = min(k, n - k)
result = 1
for i in range(1, k + 1):
result = result * (n - k + i) // i
return result
Both custom implementations assume integer inputs and reject values outside the ordinary combination domain. Prefer math.comb() for production code unless a custom calculation is needed for learning or adaptation. SciPy is appropriate when its numeric APIs fit a larger scientific workflow; math.factorial() illustrates the formula, while the multiplicative product avoids forming the full factorials.