Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum a 2d array in Python?

Tags:

python

I want to sum a 2 dimensional array in python:

Here is what I have:

def sum1(input):
    sum = 0
    for row in range (len(input)-1):
        for col in range(len(input[0])-1):
            sum = sum + input[row][col]

    return sum


print sum1([[1, 2],[3, 4],[5, 6]])

It displays 4 instead of 21 (1+2+3+4+5+6 = 21). Where is my mistake?

like image 835
Ronaldinho Learn Coding Avatar asked May 23 '12 03:05

Ronaldinho Learn Coding


People also ask

How do you sum a row in a 2D array Python?

Sum of every row in a 2D array To get the sum of each row in a 2D numpy array, pass axis=1 to the sum() function. This argument tells the function of the axis along which the elements are to be summed.


2 Answers

I think this is better:

 >>> x=[[1, 2],[3, 4],[5, 6]]                                                   
>>> sum(sum(x,[]))                                                             
21
like image 190
hit9 Avatar answered Oct 01 '22 14:10

hit9


You could rewrite that function as,

def sum1(input):
    return sum(map(sum, input))

Basically, map(sum, input) will return a list with the sums across all your rows, then, the outer most sum will add up that list.

Example:

>>> a=[[1,2],[3,4]]
>>> sum(map(sum, a))
10
like image 20
machow Avatar answered Oct 01 '22 14:10

machow