How to Count the Number of Combinations in Python?

Estimated read time 1 min read

To count the number of combinations in Python, you can use the combinations() function from the itertools module. The combinations() function takes two arguments: an iterable (e.g., a list, tuple, or string) and an integer r that specifies the length of each combination.

Here’s an example:

from itertools import combinations

# count the number of combinations of length 2 in a list of 4 elements
lst = [1, 2, 3, 4]
count = len(list(combinations(lst, 2)))

print(count)

In this example, we have a list of 4 elements [1, 2, 3, 4] and we want to count the number of combinations of length 2. We pass the list and the value 2 to the combinations() function, which generates all possible combinations of length 2. We then convert the resulting iterator to a list and use the len() function to count the number of elements in the list.

The output of the example will be:

6

In this output, we can see that there are 6 possible combinations of length 2 in the list [1, 2, 3, 4]. If we wanted to count the number of combinations of a different length, we would simply change the value of r passed to the combinations() function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply