mama dede
mama dede

Reputation: 360

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]

Upvotes: 2

Views: 656

Answers (1)

yatu
yatu

Reputation: 88305

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]

Upvotes: 3

Related Questions