How to multiply every N consecutive items in a list with Python

1 Answer

0 votes
from itertools import tee
from math import prod

def products_n_consecutive_items(lst, n):
    iters = tee(lst, n)
    for i, it in enumerate(iters):
        for _ in range(i):
            next(it, None)
            
    return [prod(group) for group in zip(*iters)]


total_consecutive_items = 3
lst = [2, 3, 4, 5, 6, 7, 8, 9, 10]

print(products_n_consecutive_items(lst, total_consecutive_items))

# 2 * 3 * 6 = 24
# 3 * 4 * 5 = 60
# 4 * 5 * 6 = 120
# 5 * 6 * 7 = 210
# 6 * 7 * 8 = 336
# 7 * 8 * 9 = 504
# 8 * 9 * 10 = 720

'''
run:

[24, 60, 120, 210, 336, 504, 720]

'''

 



answered Jan 31 by avibootz

Related questions

...