snippetpythonCriticalCanonical
How to get all possible (2^N) combinations of a list’s elements, of any length
Viewed 0 times
possiblehowanylistelementslengthallcombinationsget
Problem
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)?
How can I do it? Would 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 work?
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".
How can I do it? Would 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 work?
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:
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!
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!
Code Snippets
itertools.combinations(iterable, r)Context
Stack Overflow Q#464864, score: 705
Revisions (0)
No revisions yet.