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

This answer missed one aspect: the OP asked for ALL combinations… not just combinations of length “r”.

So you’d either have to loop through all lengths “L”:

import itertools

stuff = [1, 2, 3]
for L in range(len(stuff) + 1):
    for subset in itertools.combinations(stuff, L):
        print(subset)

Or — if you want to get snazzy (or bend the brain of whoever reads your code after you) — you can generate the chain of “combinations()” generators, and iterate through that:

from itertools import chain, combinations
def all_subsets(ss):
    return chain(*map(lambda x: combinations(ss, x), range(0, len(ss)+1)))

for subset in all_subsets(stuff):
    print(subset)

Leave a Comment