How to sum elements of a list of lists?
An alternative is
Plus @@ # & /@ Transpose@myList
This is twice as slow for small lists like yours. For big lists it is more efficient:
biglist = RandomInteger[{0, 9}, {10000, 2}];
Plus @@ biglist // RepeatedTiming
Plus @@ # & /@ Transpose@biglist // RepeatedTiming
0.0068
0.0013
(Revised) Update
(see edits for history)
For lists containing more than ~14 (n = 2) sublists my method is quicker than Plus@@
. However, as @Carl Woll points out, one must consider array unpacking with certain Mathematica functions.
(a good discussion of packed versus unpacked arrays can be found here)
sublistsum1 =
Transpose@
Table[Module[{list, plist, tlist, totlist, ttotlist},
list = RandomInteger[{0, 9}, {x, 2}];
plist = RepeatedTiming[Plus @@ list][[1]];
tlist = RepeatedTiming[Plus @@ # & /@ Transpose@list][[1]];
totlist = RepeatedTiming[Total[list]][[1]];
ttotlist = RepeatedTiming[Total[#] & /@ Transpose@list][[1]];
{{x, plist}, {x, tlist}, {x, totlist}, {x, ttotlist}}],
{x, 2, 30, 2}
];
ListLinePlot[sublistsum1, PlotStyle -> {Red, Blue, Green, Orange},
PlotLegends ->
{"Plus@@...", "Plus@@#&/@Transpose@...",
"Total...", "Total[#]&/@Transpose@..."},
AxesLabel -> {"Number of sublists\n(of length 2)", "Speed (seconds)"}]
For the Plus
-based methods as the sublists get longer the advantage of transposing the data diminishes.
Regardless, Total[..]
is the fastest method.
sublistsum2 =
Transpose@
Table[Module[{list, plist, tlist, totlist, ttotlist},
list = RandomInteger[{0, 9}, {10000, x}];
plist = RepeatedTiming[Plus @@ list][[1]];
tlist = RepeatedTiming[Plus @@ # & /@ Transpose@list][[1]];
totlist = RepeatedTiming[Total[list]][[1]];
ttotlist = RepeatedTiming[Total[#] & /@ Transpose@list][[1]];
{{x, plist}, {x, tlist}, {x, totlist}, {x, ttotlist}}],
{x, 10, 70, 10}];
ListLinePlot[sublistsum2, PlotStyle -> {Red, Blue, Green, Orange},
PlotLegends -> {"Plus@@...",
"Plus@@#&/@Transpose@...",
"Total...",
"Total[#]&/@Transpose@..."},
AxesLabel -> {"Length of sublists\n\[Times]10000", "Speed (seconds)"}]
myList = {{1, 0}, {2, 3}, {4, 1}}
Plus @@ myList