-2

Suppose I have two lists: a = [1, 2] and b = [3, 4, 5].

What is the Python way of making tuples (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)?

alekscooper
  • 795
  • 1
  • 7
  • 19

3 Answers3

3
[(x, y) for x in a for y in b]

gives you [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]

orangecat
  • 246
  • 1
  • 5
1

Check itertools.product() which is the exact equivalent code of the answer provided by @orangecat but it returns as iterator.

So if you want list of these you can just do the following:

  output = list(itertools.product(a, b))
the23Effect
  • 580
  • 2
  • 7
1

When the lists are bigger and u don't want to manually add all the for steps in a list comprehension u can use itertools, for example:

from itertools import product

a = [1, 2]
b = [3, 4, 5]

result = list(product(a, b))
print(result)
>>> [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
marcos
  • 4,473
  • 1
  • 10
  • 24