pythonloopspython-3.7literate-programming

Iterate function over a list


I have a list in which total number of items may change. I want to apply a function which requires two inputs on first two items in the list and with the result I want to apply the same function on the third item in the list and with the result I want to apply function for fourth and so on...

Is there a better way to do the below when you know number of items in the list

for x,y,a,b,c...n in result:
    z=np.convolve(x,y)
    z=np.convolve(z,a)
    z=np.convolve(z,b)
    z=np.convolve(z,c)
    .
    .
    .
    final=np.convolve(z,n)
print(final)

Solution

  • What you want to do is called reduce-function. Python has them.

    For your case, you can use them like this:

    from functools import reduce
    
    reduce(lambda x, y: np.convolve(x, y), result)