Make ordered pairs from two lists in Python

Question:

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)?

Asked By: alekscooper

||

Answers:

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

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

Answered By: orangecat

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))
Answered By: the23Effect

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)]
Answered By: marcos
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.