Search code examples
pythoncombinations

How to get all possible combinations of three lists


I have three lists:

list_a=[1,2]
list_b=[3,4]
list_c=[5,6]

Now i'm looking for a solution in python by using a loop where a new list iterates through all possible combinations of these three lists (the order is not important):

new_list = list_a # -> [1,2]
new_list = list_b # -> [3,4]
new_list = list_c # -> [5,6]
new_list = list_a + list_b # -> [1,2,3,4]
new_list = list_b + list_c # -> [3,4,5,6]
new_list = list_a + list_c # -> [1,2,5,6]
new_list = List_a + list_b + list_c # -> [1,2,3,4,5,6]

I found some similar posts with "itertools" or nested loops, but nothing exactly like this...


Solution

  • You can use itertools:

    from itertools import combinations, chain
    
    out = [list(chain.from_iterable(l)) 
              for i in range(3) 
              for l in combinations([list_a, list_b, list_c], i+1)]
    
    # Output
    [[1, 2],
     [3, 4],
     [5, 6],
     [1, 2, 3, 4],
     [1, 2, 5, 6],
     [3, 4, 5, 6],
     [1, 2, 3, 4, 5, 6]]