5
votes
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]
1
[(x,y) for x in a for y in b]? - Wondercricket
You can use itertools.product(): list(x for x in itertools.product([1, 2, 3], ['a', 'b'])) - John Szakmeister
@jszakmeister Or just list(itertools.product([1, 2, 3], ['a', 'b'])), ;) - schwobaseggl
Thanks Wondercricket, that's what I was looking for. @schwobaseggl does product work for n lists? Like (a,b,c) for [a][b][c], (a,b,c,d) for [a][b][c][d], etc? - Kyle K
Sigh. I don't think the referenced question is actually similar enough to this one. :-( zip() is the wrong solution here and map() isn't necessarily a better solution either. - John Szakmeister

1 Answers

15
votes

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')]