Python or math: How to count all possible combinations of a list's elements?

Say there is a list [1,2,3,4,5], I would need to get the count of all possible combinations of the elements (or ‘sub-lists’), e.g. 1, 2, 3, 4, 5, 12, 13, 14, ..., 123, 124, ..., 12345.

I know how to get nCr, the count of combinations of r elements of a list with total n elements.
Python 3.8 or above:

from math import comb
p, r = 5, 2
print(comb(p, r))

Then I could do nC1 + nC2 +...+ nCn. But is there a better/faster way?

p, result = 5, 0
for r in range(1, 6):
    result += comb(p, r)
print(result)

Would appreciate your answers.

>Solution :

This specific sum is equal to 2^n -1 🙂

Leave a Reply