11
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]
23k
  • 1,596
  • 3
  • 23
  • 52
Kyle K
  • 188
  • 1
  • 1
  • 4

1 Answers1

38

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')]
user2390182
  • 72,016
  • 6
  • 67
  • 89