Sum of All Elements

Question

How do you sum all the elements in an array?

Answer

Use the Numeric method sum:

>>> import Numeric
>>> a = Numeric.array([1, 5, -3, 2, -9])
>>> Numeric.sum(a)
-4

By default, sum does the summation along the array's index 0 axis, and thus returns an array with that dimension "removed". Thus, for a 2-D array, it sums down columns, and returns a vector with a length equal to the number of columns of the original array:

>>> b = Numeric.array( [[1,5,-3,2,-9], [4,6,-2,6,8]] )
>>> b
array([[ 1, 5, -3, 2, -9],
       [ 4, 6, -2, 6, 8]])
>>> b.shape
(2, 5)
>>> Numeric.sum(b)
array([ 5, 11, -5, 8, -1])

You can change which axis to sum over via the axis keyword:

>>> Numeric.sum(b, axis=1)
array([-4, 22])

To sum all the elements in the array, you'll need to apply sum on the flat or raveled version of the array. Remember that ravel is the better choice since it works on all arrays, where flat only works on contiguous arrays:

>>> Numeric.sum( b.flat )
18
>>> Numeric.sum( Numeric.ravel(b) )
18

Note that sum is an alias for add.reduce. The total function in IDL provides similar functionality, though for total the default is to sum over the entire array, not just the first axis.


Notes: See also Martelli (2003), pp. 324, 326.

Return to the Tips and Examples index page.

Updated: November 21, 2003 by Johnny Lin <email address>. License.