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 roll-out (NOT FLATTEN) a list of lists in Python

Say I have a list of lists:

my_list = [["a"], ["b"], ["c", "d"], ["e", "f", "g"]]

I would like a function that gives each possible combination of elements:

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

output = [["a","b","c","e"],["a","b","d","e"],["a","b","c","f"],["a","b","d","f"],["a","b","c","g"],["a","b","d","g"]]

Note that the number of elements in the initial list is the same of the number of elements in the output sublists. The number of output sublists is the product of the lengths of the input sublists.

I don’t believe this can be done through list comprehension but I may be wrong.

>Solution :

This will do the trick:

from itertools import product

list(product(*my_list))

outputs:

[('a', 'b', 'c', 'e'), ('a', 'b', 'c', 'f'), ('a', 'b', 'c', 'g'), ('a', 'b', 'd', 'e'), ('a', 'b', 'd', 'f'), ('a', 'b', 'd', 'g')]
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