How can a I sum a list in cycles

I need to create a list that sums values in ranges from x to x. For example, calculate the sum 2 by 2

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
listSum = sum(myList)
print(f"Sum of list -> {listSum}")

I want to achieve in the first iteration 1+2, in the next 3+4 until the last list value. I tried with a list compreension but i don't know how to do the sum.

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = [ i for i in range(myList[0],len(myList),2)]
print(list2)

I pretend obtain list2 = [3,7,11,15,19]

The problem em questions is ,for example, if my list has 240 values, I want to sum 60 in 60, sum in blocks of 60 values.

Can someone help me with this?


Are you expecting any leftover values? Like length 15 in blocks of 4? Ill answer this with just basic python, if you want to use numpy look at AJITHs answer.

list2 = [sum(myList[i:i+blockSize]) for i in range(len(myList)//blockSize +1)]

what you need to do is first split the original list in question in parts of size 'n'. this can be done by using list comprehension to create a list of parts of the original list.

>>> original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> n = 2 # size of each chunk
>>> splits_of_og_list = [original_list[i:i+n] for i in range(0, len(original_list), n)]
>>> splits_of_og_list
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]

replace n to whatever size you want and you will get chunks of size n.

then simply use the sum function over the splits_of_og_list.

>>> summed_list = [sum(split) for split in splits_of_og_list]
>>> summed_list
[3, 7, 11, 15, 19]

sum is an inbuilt function that returns the total of a iterable of integers.