Python math.comb() - Number of Combinations
Python math.comb()
math.comb(n, k) function returns the number of ways to select k items from n items without repeating the items and without order.
comb(n, k) = n! / ( k! * (n - k)! )
comb() function is available since Python version 3.8.
Syntax
The syntax to call comb() function is
math.comb(n, k)
where
Parameter | Required | Description |
---|---|---|
n | Yes | An integer value. |
k | Yes | An integer value. |
If n or k is not integer, then comb() raises TypeError.
If n or k is negative, then comb() raises ValueError.
If n is less than k, then comb() returns 0.
Examples
Number of combinations for selection 4 out of 9 items, without repetition and without considering order.
Python Program
import math
n = 9
k = 4
result = math.comb(n, k)
print('comb(n, k) :', result)
Output
comb(n, k) : 126
Number of combinations when n is negative.
Python Program
import math
n = -9
k = 4
result = math.comb(n, k)
print('comb(n, k) :', result)
Output
ValueError: n must be a non-negative integer
Number of combinations when n is not integer.
Python Program
import math
n = 9.2
k = 4
result = math.comb(n, k)
print('comb(n, k) :', result)
Output
TypeError: 'float' object cannot be interpreted as an integer
Number of combinations when n is less than k.
Python Program
import math
n = 2
k = 4
result = math.comb(n, k)
print('comb(n, k) :', result)
Output
comb(n, k) : 0
Summary
In this Python Examples tutorial, we learned the syntax of, and examples for math.comb() function.