How does math.comb() work in Python?

The in-built math.comb() function from the math module in Python is used to find the total number of unordered combinations to choose k amount of items from n items.

Figure 1: Mathematical expression of math.comb(), when k <= n

Syntax

math.comb(n,k)

Parameters and return values

This function requires two positive integers, n and k, as parameters.

  • If the passed parameters are negative, aValueError arises. If the parameters are not integers, a TypeError arises.

  • If k > n, 0 is returned.

Code

Example 1

import math
people = 6
chairs = 3
# Number of possible combinations of 6 different people
# being seated in 3 chairs
print(math.comb(people, chairs))

Example 2

import math
people = 6
chairs = 7
# Return value is 0 when
# k(number ofchairs) > n(number of people)
print(math.comb(people, chairs))

Free Resources