How to Multiply Lists in Python: 7 Quick Ways

by | Python

Multiplying lists in Python is a common operation when performing mathematical computations or solving problems in data manipulation. There are multiple ways to achieve this task, depending on your requirements and the libraries you have available.

To multiply lists in Python, you can use for loops, list comprehension, zip, and map functions, or the built-in functools module. You can also use functions from an external Python library like NumPy.

This article will show you many different ways to multiply lists, each with a code example and explained results.

Let’s get started!

2 Types of Numerical List Multiplication in Python

how to multiply lists in python

Before we dive into the specific methods, you should understand the type of list multiplication they achieve.

Python has several different concepts that are under the broad term of list multiplication. That includes replicating lists or achieving the Cartesian Product of elements within a list.

This article focuses instead on two types of arithmetic multiplication of elements within a list:

  1. Multiplication by value

  2. Element-wise Multiplication

Let’s take a quick look at these two concepts.

1. Multiplication By Value

When you have a list of integers, you may want to multiply each element by a specific value. For example, you have a list [1, 2, 3] and you want to multiply each element by the value 3.

You could try (incorrectly) to use the multiply operator as in this piece of code:

list1 = [1, 2, 3]
result = list1 * 3

You may be surprised that the result is [1, 2, 3, 1, 2, 3, 1, 2, 3]. This is known as list replication.

2. Element-Wise List Multiplication

Suppose you have two lists: [1, 2, 3] and [4, 5, 6]

You want to multiply the elements at the same index within the list to produce [4, 10, 18] as the result.

If you try to multiply two Python lists together using the ‘*’ operator, you’ll get an error:

TypeError: can’t multiply sequence by non-int of type ‘list’

This is because the multiplication operator isn’t designed to work with lists in the way it does with integers or floats. Instead, multiplying lists requires an operation known as element-wise multiplication.

Element-wise multiplication pairs the corresponding elements from two lists and multiplies them together, forming a new list.

Now that you understand these two concepts. let’s work through a range of techniques to achieve the correct results.

How to Use a For Loop to Multiple List Elements in Python

illustration of numbers

Suppose you want to multiply list elements by a value. For this approach, you can iterate through the elements with a for loop and multiply each one by a second value.

Here’s an example with one list. The result variable holds the output list.

list1 = [1, 2, 3, 4]
factor = 3
result = []

for element in list1:
    result.append(element * factor)

In this case, the result list will be [3, 6, 9, 12].

How to Use List Comprehensions for Multiplication

List comprehensions provide a concise way to perform the numerical type of list multiplications. You get the same result as using a for loop, but with a more compact syntax.

Here’s the previous example using list comprehension:

list1 = [1, 2, 3, 4]
factor = 3
result = [element * factor for element in list1]

This code results in the same output as before: [3, 6, 9, 12].

How to Use the Zip Function for Element-Wise Multiplication

illustration of zip function in python

If you have two lists of integers, you may want to multiply the lists element-wise. This means you multiply the first element in the first list times the first element in the second list and so on with elements in the same position.

The zip() function can achieve this when you combine it with list comprehension.

The function combines the elements of two input lists, allowing you to loop over them in parallel. Here’s an example using lists of the same size:

list1 = [1, 2, 3, 4]
list2 = [2, 3, 4, 5]
result = [a * b for a, b in zip(list1, list2)]

In this case, the result variable will hold the resultant list: [4, 10, 18].

Working With Tuples and Constructors

Sometimes, you might have to work with lists containing tuples rather than simple integers.

To multiply two lists of tuples, you can use a combination of:

  • zip() function

  • tuple constructors

  • list comprehensions

Here’s an example:

list1 = [(1, 2), (3, 4)]
list2 = [(5, 6), (7, 8)]

result = [tuple(a * b for a, b in zip(t1, t2)) for t1, t2 in zip(list1, list2)]

This is the result: [(5, 12), (21, 32)].

How to Use a Map and Lambda Function in Python

illustration of map in python

The map function in Python is a convenient way to apply a function to each item in an iterable like a list.

A lambda function in Python is a small anonymous function. This means it’s a function without a name.

To multiply two lists element-wise, you can combine map and lambda functions:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list(map(lambda x, y: x * y, list1, list2))

The result variable will hold the multiplied lists: [4, 10, 18].

How to Use the Operator Module in Python

The operator module provides a wealth of useful functions for working with different data structures and types.

The operator.mul() function can be used to multiply lists of integers when you combine it with the map function.

import operator

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

result = list(map(operator.mul, list1, list2))

In this example, you import the operator module and use the mul() function along with Python’s built-in map() function to multiply each element of the two lists.

The result variable will hold the multiplied lists: [4, 10, 18].

NumPy Library: The Array and Multiply Functions

illustration of installing numpy

The NumPy library is a powerful external library in Python, widely used for numerical computation and working with arrays. This library is especially efficient when dealing with large arrays or multidimensional arrays.

To use NumPy you can install it using pip:

pip install numpy

To perform element-wise multiplication in two lists using NumPy, follow these general steps:

  1. Convert each list into a NumPy array using numpy.array().

  2. Perform the multiplication using the NumPy multiply function.

  3. Optionally, convert the result back to a Python list using the tolist() method

Here is a code example:

import numpy as np

list1 = [1, 2, 3]
list2 = [4, 5, 6]
arr1 = np.array(list1)
arr2 = np.array(list2)

res_arr = np.multiply(arr1, arr2)
result = res_arr.tolist()

This will return the same result as in the previous examples: [4, 10, 18].

How to Combine Functools and NumPy in Python

The functools library contains a reduce function that applies a specific function cumulatively to the items in a list, reducing the list to a single value.

To multiply two lists using the reduce() function, you can combine it with the multiply function from the NumPy library.

Here is an example:

from functools import reduce
import numpy as np

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

result = reduce(np.multiply, [list1, list2])

This code imports the necessary libraries and uses the reduce() function along with numpy.multiply() to perform element-wise multiplication of the two lists.

Working With Lists and Other Data Structures in Python

Most aspects of data analytics require working with lists, sets, and other data structures. For example, you’ll put your knowledge to use when handling missing data with interpolation.

Check out this video for some advanced techniques:

Final Thoughts

You’ve learned various methods of multiplying lists arithmetically in Python. Some only use in-built modules and functions, while others rely on third-party libraries.

The ability to perform element-wise multiplication opens the door to a myriad of applications. From data analysis to machine learning, these operations are an essential part of many algorithms and computational tasks.

While this article focused on multiplication, the concepts you learned extend to other operations as well. Element-wise addition, subtraction, and division can also be accomplished in much the same way.

Remember, the best way to solidify these concepts is by applying them — so go ahead, fire up your Python environment and start experimenting. Whether you’re automating tasks, manipulating data, or building complex software, these techniques will undoubtedly come in handy.

Happy Pythoning!

Related Posts