python multiply list elements which one is faster

[Python] Multiply List Elements: Which One Is Faster? (Loop vs NumPy vs Iterative vs Reduce)

Imagine you want to multiply all elements in a Python list, like this one:

# List of the first 5 Fibonacci numbers greater than 1
fib_5 = [2, 3, 5, 8, 13]

We want to multiply every element in the list, so our result should be:

2 * 3 * 5 * 8 * 13 = 3120

We have many ways to multiply list elements in Python, including (but not limited to):

  • Looping over each list element and multiply by the current accumulated result
  • Using numpy.prod()
  • Using a custom iterative function
  • Using functools.reduce()

But which one is faster? Let’s find out.

Let’s perform 1 million iterations on Google Colab for each method, and see which on is faster using time.process_time():

import time
import numpy
import functools

fib_5 = [2, 3, 5, 8, 13]

# Loop where we multiply the current item
# by the accumulated result
def multiply_loop(lst):
  result = 1
  for i in lst:
    result *= i
  return result

# Iterative function
# We return each element in the list, multiplied by
# "the rest of the list" if its length is greater than 1
def multiply_it(lst):
  if len(lst) > 1:
    return lst[0] * multiply_it(lst[1:])
  return lst[0]

# Testing time!

# Loop
start = time.process_time()
for i in range(1_000_000):
  multiply_loop(fib_5)
print(time.process_time() - start)

# Numpy prod
start = time.process_time()
for i in range(1_000_000):
  numpy.prod(fib_5)
print(time.process_time() - start)

# Iterative function
start = time.process_time()
for i in range(1_000_000):
  multiply_it(fib_5)
print(time.process_time() - start)

# Functools reduce
start = time.process_time()
for i in range(1_000_000):
  functools.reduce((lambda a, b: a * b), fib_5)
print(time.process_time() - start)

>>> 0.39872331599998745
>>> 5.981764331999997
>>> 1.3213625869999959
>>> 0.6201540139999935

The fastest method to multiply all list elements in Python is a simple loop. It’s 15.00x faster than numpy.prod(), 3.31x faster than an iterative function and 1.56x faster than functools.reduce().

Please bear in mind that the results may vary depending on your Google Colab instance, and the list you’re multiplying.

Always test your code before using it in production – your use case may be different from this one.