Search code examples
pythoncombinations

Get all possible (2^N) combinations of a list’s elements, of any length


I have a list with 15 numbers. How can I produce all 32,768 combinations of those numbers (i.e., any number of elements, in the original order)?

I thought of looping through the decimal integers 1–32768 and using the binary representation of each numbers as a filter to pick out the appropriate list elements. Is there a better way to do it?


For combinations of a specific length, see Get all (n-choose-k) combinations of length n. Please use that question to close duplicates instead where appropriate.

When closing questions about combinatorics as duplicates, it is very important to make sure of what OP actually wants, not the words that were used to describe the problem. It is extremely common for people who want, for example, a Cartesian product (see How to get the cartesian product of multiple lists) to ask about "combinations".


Solution

  • Have a look at itertools.combinations:

    itertools.combinations(iterable, r)
    

    Return r length subsequences of elements from the input iterable.

    Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

    Since 2.6, batteries are included!