Python .comb()

aSagCoder's avatar
Published Jul 23, 2024
Contribute to Docs

In Python, the .comb() function from the math module calculates the number of ways to choose k items from n items without regard to order or repetition.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

math.comb(n, k)
  • n: A non-negative integer that represents the total number of items.
  • k: A non-negative integer that represents the number of items to choose.

The result returned is a non-negative integer representing the number of unordered choices that can be made to select k items from n items.

Example

The following example shows the use of the .comb() function:

import math
n = 10
k = 4
no_of_choices = math.comb(n,k)
print("Total ways to choose: ", no_of_choices)

This bit of code gives out the following output:

Total ways to choose: 210

Codebyte Example

The below codebyte example uses the .comb() function in order to find out in how many ways can someone choose k number of flowers from n number of flowers:

Code
Output

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours