Search code examples
pythonlistaccumulate

Multiply the first element of a list by a given number and calculate a cumulative product of the resulting list


I have the following list:

l = [1, 2, 3, 4, 5, 6]

I want to multiply the first element by 9, (1*9)=9 and then all successive items by the result of the previous multiplication. See the following output:

[9, 18, 54, 216, 1080, 6480]

Solution

  • You could update the first item in the list, and use itertools.accumulate with operator.mul to take the cumulative product of its values:

    from operator import mul
    from itertools import accumulate
    
    l = [1, 2, 3, 4, 5, 6]
    
    l[0]*=9
    list(accumulate(l, mul))
    # [9, 18, 54, 216, 1080, 6480]