Python – Product of prefix in list

Finding the product of prefix in a list means calculating cumulative products where each position contains the product of all elements from the start up to that position. Python offers several approaches to accomplish this task efficiently.

What is Product of Prefix?

Given a list, the product of prefix transforms it so that each element becomes the product of all preceding elements including itself. For example:

Original List [5, 6, 7, 8]
Product of Prefix [5, 30, 210, 1680]

The calculation works as follows:

  • Position 0: 5 = 5

  • Position 1: 5 × 6 = 30

  • Position 2: 5 × 6 × 7 = 210

  • Position 3: 5 × 6 × 7 × 8 = 1680

Using a User-Defined Function

This approach uses nested loops to calculate the cumulative product at each position ?

def prefix_product(numbers):
    result = []
    
    for i in range(len(numbers)):
        product = 1
        for j in range(i + 1):
            product *= numbers[j]
        result.append(product)
    
    return result

# Example usage
numbers = [5, 6, 7, 8]
print("Original list:", numbers)
print("Product of prefix:", prefix_product(numbers))
Original list: [5, 6, 7, 8]
Product of prefix: [5, 30, 210, 1680]

Using NumPy's cumprod() Method

NumPy provides a built-in function cumprod() that calculates cumulative products efficiently ?

import numpy as np

numbers = [5, 6, 7, 8]
prefix_products = np.cumprod(numbers)

print("Original list:", numbers)
print("Product of prefix:", prefix_products)
print("As Python list:", prefix_products.tolist())
Original list: [5, 6, 7, 8]
Product of prefix: [   5   30  210 1680]
As Python list: [5, 30, 210, 1680]

Using itertools.accumulate()

The itertools.accumulate() function with a lambda function for multiplication provides an elegant solution ?

import itertools
import operator

numbers = [5, 6, 7, 8]

# Using lambda function
prefix_products1 = list(itertools.accumulate(numbers, lambda x, y: x * y))

# Using operator.mul (more efficient)
prefix_products2 = list(itertools.accumulate(numbers, operator.mul))

print("Original list:", numbers)
print("Using lambda:", prefix_products1)
print("Using operator.mul:", prefix_products2)
Original list: [5, 6, 7, 8]
Using lambda: [5, 30, 210, 1680]
Using operator.mul: [5, 30, 210, 1680]

Performance Comparison

Method Time Complexity Best For
User-defined function O(n²) Learning purposes
NumPy cumprod() O(n) Large numerical arrays
itertools.accumulate() O(n) Pure Python, memory efficient

Conclusion

Use numpy.cumprod() for numerical computations with large datasets. For pure Python solutions, itertools.accumulate() with operator.mul offers the best performance and readability.

Updated on: 2026-03-27T14:26:39+05:30

404 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements