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(0, 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)

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!