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
