Search code examples
pythoncombinationspermutation

How to generate combinations of elements of different lists?


I have a list of lists that goes like

[[1,2,3],[3,4,5],[5,6,7,8]]

I want to create a program/function that creates a combinations like

1,3,5
1,3,6
1,3,7
1,3,8
1,4,5
1,4,6
.
.
.

If there's a way you can do it without using the itertools module, that would be even more appreciated.


Solution

  • As you asked for a solution without itertools, this one is a recursive function that takes a list of any length and does the combination you need:

    def combine(elems):
        if len(elems) == 0:
            return [[]]
        result = []    
        subcombinations =  combine(elems[1:])
        for x in elems[0]:
            for y in subcombinations:
                result.append([x, *y])
        return result
    

    Or a much shorter version

    def combine(elems):
        if len(elems) == 0:
            return [[]]
        return [[x, *y] for x in elems[0] for y in combine(elems[1:])]