Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading