Skip to content

Python multiply two lists | Example code

  • by

Use the zip() function to multiply two lists in Python. But the much better option is to use a list comprehension mixed with a zip() function.

For example, multiply two lists in Python

A simple example code multiplies two equal-length list elements from one list by the element at the same index in the other list.

Using zip with for loop

list1 = [1, 2, 3]
list2 = [4, 5, 6]

res = []

for num1, num2 in zip(list1, list2):
    res.append(num1 * num2)

print(res)

Output:

Using a list comprehension

list1 = [1, 2, 3]
list2 = [4, 5, 6]

res = [a * b for a, b in zip(list1, list2)]

print(res)

Output: [4, 10, 18]

Use np.multiply(a,b)

import numpy as np

a = [1, 2, 3, 4]
b = [2, 3, 4, 5]

res = np.multiply(a, b)
print(res)

Output: [ 2 6 12 20]

Using lambda

foo = [1, 2, 3, 4]
bar = [1, 2, 5, 55]

l = map(lambda x, y: x * y, foo, bar)

print(list(l))

Output: [1, 4, 15, 220]

Comment if you have any doubts or suggestions on this Python multiply topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading