How to multiply two lists in Python?

When we are working with Python lists, we may come across a situation where we need to multiply two lists.

List multiplication simply means multiplying the elements that are on the same index in both the lists and getting a list that contains the multiplication result.

For example, if we have two lists [1, 2, 3, 4] and [5, 6, 7, 8] then their multiplication will be [5, 12, 21, 32]. We can achieve this task in several ways. Let’s discuss the easiest ones.


Method 1: The naive approach

In this approach, we will use the range() function to loop over the two lists and then multiply the items that are on the same index.

Note that in this example both the lists are of the same size. If the two lists are of unequal length, you have to pass the length of the list with minimum numbers of items as the range() parameter.

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
result = []

for i in range(len(a)):
    result.append(a[i] * b[i])

print('Multiplication result is: ', result)    

Output:

Multiplication result is:  [5, 12, 21, 32]

Method 2: Use zip() function to multiply two lists

In the last example, we saw that if the two lists are of unequal length, we have to first find the list with minimum numbers of items to avoid any multiplication errors.

The zip() function can solve that problem. The zip() function returns a sequence of elements that are on the same index in both lists and ignores the elements that have no match.

a = [1, 2, 3, 4, 10, 20]
b = [5, 6, 7, 8]
result = []

for num1, num2 in zip(a, b):
    result.append(num1*num2)

print('Multiplication result is: ', result)    

Output:

Multiplication result is:  [5, 12, 21, 32]

Method 3: Use list comprehension to multiply two lists

If you want to write less code to get the multiplication result, list comprehension is the best choice. This is a more compact way to get the multiplication result.

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]

result = [num1*num2 for num1, num2 in zip(a,b)]

print('Multiplication result is: ', result)    

Example:

Multiplication result is:  [5, 12, 21, 32]

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.