How to Make A Combination of Lists of A List in Python

Question:

I do not know whether to call it combination or permutation, so the question can be edited regarding your comment in question.

I have a list as below:

[
    ["a"],
    ["b", "c"],
    ["d", "e", "f"]
]

I want this to output as:

[
    "abd",
    "acd",
    "abe",
    "ace",
    "abf",
    "acf"
]

My first priority is to make this with built-in tools or by hand, not with other scientific modules. However, if there is no way, scientific modules might be used.


Environment

  • python 3.5.1
Asked By: Eray Erdin

||

Answers:

As suggested by the comments, you could use itertools.product. Or you could implement a simple recursive method:

def combine(lists, index=0, combination=""):
    if index == len(lists):
        print combination
        return
    for i in lists[index]:
        combine(lists, index+1, combination + i)

lists = [
    ["a"],
    ["b", "c"],
    ["d", "e", "f"]
]

combine(lists)
Answered By: Bhavana