Borislav Hadzhiev
Last updated: Jul 9, 2022
Check out my new book
To multiply two lists element-wise:
zip
function to get an iterable of tuples with the corresponding
items.list_1 = [1, 2, 3] list_2 = [4, 5, 6] # 👇️ [(1, 4), (2, 5), (3, 6)] print(list(zip(list_1, list_2))) result = [x * y for x, y in zip(list_1, list_2)] print(result) # 👉️ [4, 10, 18]
The zip function iterates over several iterables in parallel and produces tuples with an item from each iterable.
list_1 = [1, 2, 3] list_2 = [4, 5, 6] # 👇️ [(1, 4), (2, 5), (3, 6)] print(list(zip(list_1, list_2)))
You can imagine that the zip()
function iterates over the lists, taking 1 item
from each.
0
, the second tuple consists of the elements in each list that have an index of 1
, etc.The last step is to use a list comprehension to iterate over the zip
object
and multiply the values in each tuple.
list_1 = [1, 2, 3] list_2 = [4, 5, 6] # 👇️ [(1, 4), (2, 5), (3, 6)] print(list(zip(list_1, list_2))) result = [x * y for x, y in zip(list_1, list_2)] print(result) # 👉️ [4, 10, 18]
On each iteration, we unpack the values from the tuple and use the
multiplication *
operator to multiply them.
a, b = (2, 5) print(a * b) # 👉️ 10
You can also use this approach to multiply more than two lists element-wise.
list_1 = [1, 2, 3] list_2 = [4, 5, 6] list_3 = [7, 8, 9] # 👇️ [(1, 4, 7), (2, 5, 8), (3, 6, 9)] print(list(zip(list_1, list_2, list_3))) result = [x * y * z for x, y, z in zip(list_1, list_2, list_3)] print(result) # 👉️ [28, 80, 162]
Alternatively, you can use the map()
function.
To multiply two lists element-wise:
map()
function to call the mul()
function with the two lists.list()
class to convert the map
object to a list.from operator import mul list_1 = [1, 2, 3] list_2 = [4, 5, 6] result = list(map(mul, list_1, list_2)) print(result) # 👉️ [4, 10, 18]
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
The mul
function from the operator
module is the same as a * b
.
map
calls the mul
function with each item of the two iterables (e.g. items at index 0
, then 1
, etc).The map
function returns a map
object, so we had to use the list()
class
to convert the result to a list.