# Sum of list elements in a range

I have a list, for example:

data = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};


and I wanted to sum every element in range of five, i. e

ranges

{1,2,3,4,5} and {6,7,8,9,10} and {11,12,13,14,15} and {16,17,18,19,20}

and the result I want to get is:

{34, 38, 42, 46, 50}

• Try Total[Partition[data, 5], {1}] Commented Jan 18, 2022 at 0:16
• Or Total@GatherBy[data, Floor[(# - 1)/5] &] Commented Jan 18, 2022 at 0:47
• Or Plus @@@ Transpose@Partition[data, 5]. Commented Jan 18, 2022 at 0:54
• Oof. Lemme get a valid one in: Plus@@data[[#;;;;5]]&/@Range@5
Commented Jan 18, 2022 at 1:07
• {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20} // Partition[#,5]& // MapThread[Plus] Commented Apr 10, 2022 at 11:59

## There are three ways that yield the desired outut: 1. Last@Accumulate@list Plus@@list and Total@list

Various approaches to get the list mentioned above

## 0. InternalPartitionRagged

Last@Accumulate@
InternalPartitionRagged[data, Table[5, Length@data/5]]


also

Plus @@ InternalPartitionRagged[data, Table[5, Length@data/5]]


and

Total@InternalPartitionRagged[data,
Table[5, Length@data/5]]


## 1. ArrayReshape

Last@Accumulate@ArrayReshape[data, {Length@data/5, 5}]


also

Plus @@ ArrayReshape[data, {Length@data/5, 5}]


and

Total@ArrayReshape[data, {Length@data/5, 5}]


## 2. Fold + Partition + Flatten

Last@Accumulate@
Fold[Partition, Flatten[data], {Length@data/5, 5}[[-1 ;; 2 ;; -1]]]


also

Plus @@ Fold[Partition,
Flatten[data], {Length@data/5, 5}[[-1 ;; 2 ;; -1]]]


and

Total@Fold[Partition,
Flatten[data], {Length@data/5, 5}[[-1 ;; 2 ;; -1]]]


## 3. TakeList

Last@Accumulate@TakeList[data, Table[5, Length@data/5]]


also

Plus @@ TakeList[data, Table[5, Length@data/5]]


and

Total@TakeList[data, Table[5, Length@data/5]]


## 4. FoldPairList + TakeDrop

Last@Accumulate@FoldPairList[TakeDrop, data, Table[5, Length@data/5]]


also

Plus @@ FoldPairList[TakeDrop, data, Table[5, Length@data/5]]


and

Total@FoldPairList[TakeDrop, data, Table[5, Length@data/5]]


All of the above and the solutions suggested in the comments section give

I will update the timings later tonight

data = Range[20];


Using MovingMap:

Total@MovingMap[# &, data, 4][[1 ;; -1 ;; 5]]

(*{34, 38, 42, 46, 50}*)


Or using BlockMap:

Total@BlockMap[# &, data, 5]

(*(*{34, 38, 42, 46, 50}*)*)

data = Range[20];


Using SequenceCases

Total @ SequenceCases[data, {Repeated[_, {5}]}]


{34, 38, 42, 46, 50}

Total @ SequenceCases[data, _?(Length[#] == 5 &)]


{34, 38, 42, 46, 50}

Using ArrayReduce and Partition:

data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20};

Partition[data, 5] // ArrayReduce[Total, #, 1] &


Using MapThread:

MapThread[Plus@## &, Partition[data, 5]]


Result:

{34, 38, 42, 46, 50}