Reputation: 5354
I am trying to make all the possible combinations of a list. like:
l= [1,4,6,8,11,13]
combL = [ [1],[4],[6],[8],[11],[13],[1,4], .. ]
I tried to use
itertools.combinations(l, len(l))
but it didn't work out. Any function on Python that do that ?
Upvotes: 0
Views: 230
Reputation: 13539
as a list:
[i for j in xrange(len(l)) for i in itertools.combinations(l, j+1)]
or as a generator:
(i for j in xrange(len(l)) for i in itertools.combinations(l, j+1))
Upvotes: 1
Reputation: 8159
res = []
for L in range(0, len(l)+1):
for subset in itertools.combinations(l, L):
res.append(list(subset))
Output:
[[], [1], [4], [6], [8], [11], [13], [1, 4], [1, 6], [1, 8], [1, 11], [1, 13], [4, 6], [4, 8], [4, 11],....
Upvotes: 0
Reputation: 239433
from itertools import combinations
def get_all_combinations(input_list):
for i in xrange(len(input_list)):
for item in combinations(input_list, r = i + 1):
yield list(item)
input_list = [1,4,6,8,11,13]
for item in get_all_combinations(input_list):
print item
We have created a generator, so it is efficient as we don't have to store the entire combinations in memory. It is important for a combinations generator, because, often the number of combinations is very big.
But if you want to get all the combinations as list, then you can do
list(get_all_combinations(input_list))
# [[1], [4], [6], [8], [11], [13], [1, 4], [1, 6], [1, 8], [1, 11], [1, 13],..]
Upvotes: 5