0

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 ?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
user3378649
  • 5,154
  • 14
  • 52
  • 76
  • 3
    Possible duplicate? http://stackoverflow.com/questions/8371887/making-all-possible-combinations-of-a-list-in-python – Germano Mar 18 '14 at 09:31
  • 1
    Does this answer your question? [Making all possible combinations of a list](https://stackoverflow.com/questions/8371887/making-all-possible-combinations-of-a-list) – AMC Dec 07 '19 at 04:39

3 Answers3

5
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],..]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

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))
M4rtini
  • 13,186
  • 4
  • 35
  • 42
0
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],....
Anish Shah
  • 7,669
  • 8
  • 29
  • 40