Here are two concise approaches.
The first uses itertools.product()
and a list comprehension:
from itertools import product
[x * y for x, y in product(list1, list2)]
But, this problem is very well-suited for itertools.starmap()
, which motivates the second approach. If you're unfamiliar with the function, it takes in two parameters:
- A function that takes in two parameters. In this case, we use
operator.mul
, a version of the multiplication operator that we can pass into a function. Note that functions can be passed into other functions in Python because functions are first class.
- An iterable of iterables of size two. In this case, it's our output from
itertools.product()
.
For each element in our iterable, it unpacks the element and passes each element as a parameter into the function specified by the first parameter. This gives us:
from itertools import product, starmap
import operator
list(starmap(operator.mul, product(list1, list2)))
Both of these output:
[12, 4, 36, 8, 6, 2, 18, 4, 21, 7, 63, 14]
If you want to extend this approach to more than two iterables, you can do (as suggested by flakes):
from math import prod
list(map(prod, product(list1, list2, <specify more iterables>)))
Other answers have suggested using multiple for
loops inside the comprehension. Note that some consider this approach to be poor style; the use of itertools.product()
avoids this issue entirely.
If you have any questions, feel free to comment -- I'm more than happy to clarify any confusion. I realize that these solutions may not be the most beginner-friendly. At the very least, I hope that these approaches may be useful for future readers.