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

Create list of all possible tuples from lists

I would like to create a list of 3-tuples in Python. These 3-tuples should hold all possible combinations of numbers, where at least one item from each list is included.
Is there any way to do this in an efficient manner?

I only thought of the possibility of nested for loops, like this:

def triplets_dos_listas(L1,L2):
    triplets = []
    #create list triplets
    for i in range(len(L1)):
        #add triplet to list triplets for all triplets with one from l1 and 2 l2
        for j in range(len(L2)):
            for k in range(len(L2)):
                triplets += tuple([L1[i], L2[j],L2[k]])
 
 
    #repeat the process for the combinations (L1,L2,L1), (L2,L1,L1) and (L2,L2,L1)
    print(triplets)

However, this seems very inefficient. Also, when I try to run this, triplets is not a list of tuples but a list of single numbers, what did I do wrong there?

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 :

With itertools.product, I guess you could do something like this:

from itertools import product
l1 = [1, 2, 3]
l2 = [4, 5]

result = product(l1, l2, l2)
print(list(result))

Previous code prints:

[(1, 4, 4), (1, 4, 5), (1, 5, 4), (1, 5, 5), (2, 4, 4), (2, 4, 5), (2, 5, 4), (2, 5, 5), (3, 4, 4), (3, 4, 5), (3, 5, 4), (3, 5, 5)]
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