RandomCoder
RandomCoder

Reputation: 2199

Python Multiplication of Two Lists

I have two lists:

list_a = list_b = list(range(2, 6)) final_list = []

I was wondering how to multiply all of the values in both lists together. I want my final_list to contain

[2*2, 2*3, 2*4, 2*5, 3*2, 3*3, 3*4, 3*5, 4*2, 4*3, 4*4, 4*5, 5*2, 5*3, 5*4, 5*5]

Upvotes: 1

Views: 299

Answers (2)

Eugene Yarmash
Eugene Yarmash

Reputation: 149756

You could use a list comprehension:

>>> list_a = list_b = list(range(2, 6))
>>> [x*y for x in list_a for y in list_b]
[4, 6, 8, 10, 6, 9, 12, 15, 8, 12, 16, 20, 10, 15, 20, 25]

Note that list_a = list_b = list(range(2, 6)) makes both variables point to the same list object. If this is not desirable, use separate lists:

>>> list_a, list_b = list(range(2, 6)), list(range(2, 6))

Upvotes: 9

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23203

itertools.product may be used to get cartesian product from arbitrary number of iterables.

import itertools
l1 = range(2,6)
l2 = range(2,6)
result = [x*y for x, y in itertools.product(l1, l2)]

To handle general case you may use reduce approach. This will work fine for arbitrary number of input sequences.

import functools
import operator
import itertools
result = [functools.reduce(operator.mul, operands)
          for operands in itertools.product(l1, l2)]

Upvotes: 5

Related Questions