How to multiply a range in Python

avatar

Borislav Hadzhiev

Last updated: Jul 9, 2022

banner

Photo from Unsplash

Multiply a range in Python #

Use a list comprehension to multiply each number in a range by specific number, e.g. result = [num * 2 for num in range(1, 6)]. The list comprehension iterates over the range and uses the multiplication * operator to multiply the current number by another number.

main.py
import math result = [num * 2 for num in range(1, 6)] # ✅ multiply each number in range by specific number print(result) # 👉️ [2, 4, 6, 8, 10] # ------------------------------------------------------- # ✅ multiply all numbers in a range print(math.prod(range(1, 5))) # 👉️ 24 (same as 1 * 2 * 3 * 4)

We used a list comprehension to iterate over a range and multiply its values by another number.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

The range class is commonly used for looping a specific number of times in for loops and takes the following arguments:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

Notice that the start value in the range is inclusive, whereas the stop value is exclusive.

main.py
# 👇️ [1, 2, 3, 4, 5] print(list(range(1, 6)))

If you only pass a single argument to the range() constructor, it is considered to be the value for the stop parameter.

main.py
# 👇️ [0, 1, 2, 3, 4, 5] print(list(range(6)))
The example shows that if the start argument is omitted, it defaults to 0 and if the step argument is omitted, it defaults to 1.

If the value for the stop parameter is lower than the value for the start parameter, the range will be empty.

main.py
# 👇️ [] print(list(range(6, 1)))

Use the math.prod() method to multiply all of the numbers in a range, e.g. math.prod(range(1, 5)). The math.prod method calculates the product of all of the items in the iterable.

main.py
import math print(math.prod(range(1, 5))) # 👉️ 24 (same as 1 * 2 * 3 * 4) print(math.prod(range(1, 4))) # 👉️ 6 (same as 1 * 2 * 3)

The math.prod method calculates the product of all the elements in the provided iterable.

main.py
import math my_tuple = (5, 5, 5) result = math.prod(my_tuple) print(result) # 👉️ 125

The method takes the following 2 arguments:

NameDescription
iterableAn iterable whose elements to calculate the product of
startThe start value for the product (defaults to 1)

If the iterable is empty, the start value is returned.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.