Get all possible (2^N) combinations of a list’s elements, of any length
To generate every combination from a list, use Python's itertools.chain
and itertools.combinations
in a comprehension:
Voila! This generates the power set of [1, 2, 3]
, providing 2^N combinations, inclusively from an empty set to a full set.
Broaden your toolkit
Catering to Originality: Handling Uniqueness and Order
Before hopping into combination generation, ensure the input list is sorted and unique:
This magic trick presents a list of ordered combinations while dodging repetitions. Now we're talking!
Just Right: Generating Specific Length Combinations
Need combinations of a specific length? Python's got your back:
You will get combinations that only Goldilocks would love - length 2, like [1, 2]
, [1, 3]
, [2, 3]
.
Channel the snake: Recursive Python Approach
Are you those who dig custom implementations? Time to get recursive:
This custom method gives you an inside peek at how combinations are built from scratch.
More tricks to master
Squeezing more: Compressive Powerset with product
An alternative approach to generating all combinations is via itertools.product
and itertools.compress
:
By leveraging a binary mask from itertools.product
, you can emulate an element's presence or absence in the combinations.
Back to Origins: Recursive combination generation
Have delight with recursion:
The equation is simple: recursion + subsets = all potential combinations.
Was this article helpful?