# List of tuples: group by first element of tuple; sum up the second element per group [duplicate]

Imagine following list

list = {{0, 3}, {1, 1}, {1, 2}, {2, 3}, {2, 4}}


I would like to get the result

{{0, 3}, {1, 3}, {2, 7}}


i.e., grouping by the first element of the tuples in the list, summing the second element of all tuples that share the same first element.

• Try KeyValueMap[List, Total /@ GroupBy[list, First -> Last]]. – J. M.'s discontentment May 25 '17 at 16:39
• @J.M. GroupBy also accepts a reduce argument, even simpler then KeyValueMap[List, GroupBy[list, First -> Last, Total]] – swish May 25 '17 at 17:20
• @swish, ah, that's even better! – J. M.'s discontentment May 25 '17 at 17:28
• {#1[[1, 1]], Total[#[[2]]]} & /@ Transpose /@ GatherBy[list, First] works in versions older than V10. – m_goldberg May 25 '17 at 19:01
• {#[[1, 1]], Total[#[[All, 2]]]} & /@ GatherBy[list, First] – Bob Hanlon May 25 '17 at 19:18

Summary of the methods given in the comments to the question.

data = {{0, 3}, {1, 1}, {1, 2}, {2, 3}, {2, 4}};


swish (requires V10 or later)

KeyValueMap[List, GroupBy[data, First -> Last, Total]]


m_goldberg (requires V7 or later)

{#1[[1, 1]], Total[#[[2]]]} & /@ Transpose /@ GatherBy[data, First]


Mr.Wizard

Rule @@@ list // Merge[Total] // KeyValueMap[List]


All the above return

{{0, 3}, {1, 3}, {2, 7}}