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)
?
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)
?
[(x, y) for x in a for y in b]
gives you [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
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))
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)]