How to multiply a range in Python


Borislav Hadzhiev

Last updated: Jul 9, 2022


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.
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(, 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:

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.
# 👇️ [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.
# 👇️ [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.
# 👇️ [] print(list(range(6, 1)))

Use the method to multiply all of the numbers in a range, e.g., 5)). The method calculates the product of all of the items in the iterable.
import math print(, 5))) # 👉️ 24 (same as 1 * 2 * 3 * 4) print(, 4))) # 👉️ 6 (same as 1 * 2 * 3)

The method calculates the product of all the elements in the provided iterable.
import math my_tuple = (5, 5, 5) result = print(result) # 👉️ 125

The method takes the following 2 arguments:

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.