Search code examples
pythonlistsummultiplication

How to multiply the two nearby elements in a list?


I have a list like below:

a = [ 1, 2 , 3, 4, s, s+1] 

I want to keep the first two elements and then multiply the rest two nearby elements. The result would be like below:

b = [1, 2, 12, s**2 + s]

I know if I want the summation, I can use the code below:

b = [*a[:2], *map(sum, (a[i: i + 2] for i in range(2, len(a), 2)))]
print (b)

and I will get the result which is : [1, 2, 7, 2*s + 1] However, I don't know how to get the multpilication result. Thanks


Solution

  • Define a customized multiplication function:

    def mul(lst):
        s = 1
        for x in lst:
            s *= x
        return s
    
    [*a[:2], *map(mul, (a[i: i + 2] for i in range(2, len(a), 2)))]