Create list of all possible tuples from lists

Question:

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?

Asked By: Rosarosa

||

Answers:

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)]
Answered By: ndclt

You can use a simple list comprehension:

def triplets_dos_listas(l1, l2):
    return [(a,b,c) for a in l1 for b in l2 for c in l2]
Answered By: Manfred
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.