0

Say I have a list of lists:

my_list = [["a"], ["b"], ["c", "d"], ["e", "f", "g"]]

I would like a function that gives each possible combination of elements:

output = [["a","b","c","e"],["a","b","d","e"],["a","b","c","f"],["a","b","d","f"],["a","b","c","g"],["a","b","d","g"]]

Note that the number of elements in the initial list is the same of the number of elements in the output sublists. The number of output sublists is the product of the lengths of the input sublists.

I don't believe this can be done through list comprehension but I may be wrong.

Mike J
  • 47
  • 7

1 Answers1

2

This will do the trick:

from itertools import product

list(product(*my_list))

outputs:

[('a', 'b', 'c', 'e'), ('a', 'b', 'c', 'f'), ('a', 'b', 'c', 'g'), ('a', 'b', 'd', 'e'), ('a', 'b', 'd', 'f'), ('a', 'b', 'd', 'g')]
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28