-2

On python, I can use the combinations function from itertools to get all the possible couples in a list. But is there a way to get all the combinations possible taking one element in a list and the other in another list?

l1 = [1,2,3]
l2 = [4,5]

Is there a function that would return

(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)
thefourtheye
  • 221,210
  • 51
  • 432
  • 478
bigTree
  • 2,032
  • 6
  • 26
  • 45

1 Answers1

3

You are look for the "Cartesian Product":

itertools.product(list1, list2, ...)

Example

from itertools import product

l1 = [1,2,3]
l2 = [4,5]

>>> print list(product(l1, l2))
[(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
Community
  • 1
  • 1
sshashank124
  • 29,826
  • 8
  • 62
  • 75