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 zip() function.

Example multiply two lists in Python

Simple example code multiplies two equal length lists element 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]

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

Note: IDE: PyCharm 2021.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

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.