You're not looking for combinations
of elements from an existing collection, but for all possible product
s of the elements of that collection:
import itertools
stuff = ['a', 'b', 'c']
for n in range(0, len(stuff) + 1):
for result in itertools.product(stuff, repeat=n):
print(result)
Output:
()
('a',)
('b',)
('c',)
('a', 'a')
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'b')
('b', 'c')
('c', 'a')
('c', 'b')
('c', 'c')
('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'a')
('a', 'b', 'b')
('a', 'b', 'c')
('a', 'c', 'a')
('a', 'c', 'b')
('a', 'c', 'c')
('b', 'a', 'a')
('b', 'a', 'b')
('b', 'a', 'c')
('b', 'b', 'a')
('b', 'b', 'b')
('b', 'b', 'c')
('b', 'c', 'a')
('b', 'c', 'b')
('b', 'c', 'c')
('c', 'a', 'a')
('c', 'a', 'b')
('c', 'a', 'c')
('c', 'b', 'a')
('c', 'b', 'b')
('c', 'b', 'c')
('c', 'c', 'a')
('c', 'c', 'b')
('c', 'c', 'c')
Note: I renamed L
to n
, because it's generally not a good idea to name variables and functions in Python with capitals and I renamed subset
to result
because what both combinations
and product
produce are not set
s but tuple
s.
As @mozway correctly points out, you may consider an example like ('a', 'b')
and ('b', 'a')
duplicates, in which case you want combinations_with_replacement
:
import itertools
stuff = ['a', 'b', 'c']
for n in range(0, len(stuff) + 1):
for result in itertools.combinations_with_replacement(stuff, r=n):
print(result)
Output:
()
('a',)
('b',)
('c',)
('a', 'a')
('a', 'b')
('a', 'c')
('b', 'b')
('b', 'c')
('c', 'c')
('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'b')
('a', 'b', 'c')
('a', 'c', 'c')
('b', 'b', 'b')
('b', 'b', 'c')
('b', 'c', 'c')
('c', 'c', 'c')