Search code examples
pythonlistpython-itertools

Combine all elements of n lists in python


there are a lot of questions and answers about combining and merging lists in python but I have not found a way to create a full combination of all elements.

If I had a list of lists like the following:

data_small = [ ['a','b','c'], ['d','e','f'] ]
data_big = [ ['a','b','c'], ['d','e','f'], ['u','v','w'], ['x','y','z'] ]

How can I get a list of lists with all combinations? For data_small this should be:

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

This should also work for an arbitrary number of lists of the same length like data_big.

I am pretty sure there is a fancy itertools solution for this, right?


Solution

  • I think I deciphered the question:

    def so_called_combs(data):
        for sublist in data:
            for sbl in data:
                if sbl==sublist:
                    yield sbl
                    continue
                for i in range(len(sublist)):
                    c = sublist[:]
                    c[i] = sbl[i]
                    yield c
    

    This returns the required list, if I understood it correctly:

    For every list in the data, every element is replaced (but only one at a time) with the corresponding element (same position) in each of the other lists.

    For data_big, this returns:

    [['a', 'b', 'c'], ['d', 'b', 'c'], ['a', 'e', 'c'], ['a', 'b', 'f'],
     ['u', 'b', 'c'], ['a', 'v', 'c'], ['a', 'b', 'w'], ['x', 'b', 'c'],
     ['a', 'y', 'c'], ['a', 'b', 'z'], ['a', 'e', 'f'], ['d', 'b', 'f'],
     ['d', 'e', 'c'], ['d', 'e', 'f'], ['u', 'e', 'f'], ['d', 'v', 'f'], 
     ['d', 'e', 'w'], ['x', 'e', 'f'], ['d', 'y', 'f'], ['d', 'e', 'z'],
     ['a', 'v', 'w'], ['u', 'b', 'w'], ['u', 'v', 'c'], ['d', 'v', 'w'],
     ['u', 'e', 'w'], ['u', 'v', 'f'], ['u', 'v', 'w'], ['x', 'v', 'w'],
     ['u', 'y', 'w'], ['u', 'v', 'z'], ['a', 'y', 'z'], ['x', 'b', 'z'],
     ['x', 'y', 'c'], ['d', 'y', 'z'], ['x', 'e', 'z'], ['x', 'y', 'f'],
     ['u', 'y', 'z'], ['x', 'v', 'z'], ['x', 'y', 'w'], ['x', 'y', 'z']]