'Combinations of 2 lists [duplicate]

Input: [1, 2, 3] [a, b]

Expected Output: [(1,a),(1,b),(2,a),(2,b),(3,a),(3,b)]

This works, but is there a better way without an if statement?

[(x,y) for (x,y) in list(combinations(chain(a,b), 2)) if x in a and y in b]


Solution 1:[1]

Use itertools.product, your handy library tool for a cartesian product:

from itertools import product

l1, l2 = [1, 2, 3], ['a', 'b']
output = list(product(l1, l2))
# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2390182