18

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?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Ronaldinho Learn Coding
  • 13,254
  • 24
  • 83
  • 110
  • 2
    `reduce(lambda x, y: x + sum(y), [[1, 2],[3, 4],[5, 6]], 0)` :-). But yeah, problem is in your range as others pointed out. – Vikas May 23 '12 at 03:54

16 Answers16

55

I think this is better:

 >>> x=[[1, 2],[3, 4],[5, 6]]                                                   
>>> sum(sum(x,[]))                                                             
21
hit9
  • 842
  • 8
  • 12
39

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
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
machow
  • 1,034
  • 1
  • 10
  • 16
10

And numpy solution is just:

import numpy as np
x = np.array([[1, 2],[3, 4],[5, 6]])

Result:

>>> b=np.sum(x)
   print(b)
21
MAYUR K
  • 3
  • 2
Akavall
  • 82,592
  • 51
  • 207
  • 251
  • 2
    If your find you are using `isinstance` for a problem as simple as this, you are probably thinking in a strongly-typed fashion. This is an overly complex answer. – msw May 23 '12 at 04:01
  • @msw, true, but using recursion this way has its advantages, since it is more flexible, as I showed it works for any strange forms of list. But at least another part of my answer was simple :). – Akavall May 23 '12 at 04:19
  • It is indeed more flexible. I have found that on stackoverflow and in coding generally, that excessive flexibility is sometimes a burden. For example, I'd rather see `sum([1, [2, 3]])` raise a TypeError than guess at what I intended. This is particularly relevant for novice questions on SO. – msw May 23 '12 at 04:30
10

This is yet another alternate Solution

In [1]: a=[[1, 2],[3, 4],[5, 6]]
In [2]: sum([sum(i) for i in a])
Out[2]: 21
Ajay
  • 5,267
  • 2
  • 23
  • 30
7

Better still, forget the index counters and just iterate over the items themselves:

def sum1(input):
    my_sum = 0
    for row in input:
        my_sum += sum(row)
    return my_sum

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

One of the nice (and idiomatic) features of Python is letting it do the counting for you. sum() is a built-in and you should not use names of built-ins for your own identifiers.

msw
  • 42,753
  • 9
  • 87
  • 112
6

This is the issue

for row in range (len(input)-1):
    for col in range(len(input[0])-1):

try

for row in range (len(input)):
    for col in range(len(input[0])):

Python's range(x) goes from 0..x-1 already

range(...) range([start,] stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
dfb
  • 13,133
  • 2
  • 31
  • 52
1

range() in python excludes the last element. In other words, range(1, 5) is [1, 5) or [1, 4]. So you should just use len(input) to iterate over the rows/columns.

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

    return sum
spinlok
  • 3,561
  • 18
  • 27
1

Don't put -1 in range(len(input)-1) instead use:

range(len(input))

range automatically returns a list one less than the argument value so no need of explicitly giving -1

Kartik Anand
  • 4,513
  • 5
  • 41
  • 72
1

Quick answer, use...

total = sum(map(sum,[array]))

where [array] is your array title.

Nuwan Alawatta
  • 1,812
  • 21
  • 29
  • 1
    Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made. – NOhs Apr 01 '18 at 22:26
1
def sum1(input):
    return sum([sum(x) for x in input])
J F Fitch
  • 116
  • 1
  • 3
1

In Python 3.7

import numpy as np
x = np.array([ [1,2], [3,4] ])
sum(sum(x))

outputs

10
Rich006
  • 143
  • 5
1

Speed comparison

import random
import timeit
import numpy
x = [[random.random() for i in range(100)] for j in range(100)]
xnp = np.array(x)

Methods

print("Sum python array:")
%timeit sum(map(sum,x))
%timeit sum([sum(i) for i in x])
%timeit sum(sum(x,[]))
%timeit sum([x[i][j] for i in range(100) for j in range(100)])

print("Convert to numpy, then sum:")
%timeit np.sum(np.array(x))
%timeit sum(sum(np.array(x)))

print("Sum numpy array:")
%timeit np.sum(xnp)
%timeit sum(sum(xnp))

Results

Sum python array:
130 µs ± 3.24 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
149 µs ± 4.16 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
3.05 ms ± 44.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.58 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Convert to numpy, then sum:
1.36 ms ± 90.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.63 ms ± 26.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Sum numpy array:
24.6 µs ± 1.95 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
301 µs ± 4.78 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Erik
  • 31
  • 6
  • 1
    [A code-only answer is not high quality](//meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers). While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please [edit] your answer to include explanation and link to relevant documentation. – Muhammad Mohsin Khan Apr 06 '22 at 12:07
0

It seems like a general consensus is that numpy is a complicated solution. In comparison to simpler algorithms. But for the sake of the answer being present:

import numpy as np


def addarrays(arr):

    b = np.sum(arr)
    return sum(b)


array_1 = [
  [1, 2],
  [3, 4],
  [5, 6]
]
print(addarrays(array_1))

This appears to be the preferred solution:

x=[[1, 2],[3, 4],[5, 6]]                                                   
sum(sum(x,[]))                                                             
peyo
  • 351
  • 4
  • 15
0
def sum1(input):
    sum = 0
    for row in input:
        for col in row:
            sum += col
    return sum
print(sum1([[1, 2],[3, 4],[5, 6]]))
Sefan
  • 699
  • 1
  • 8
  • 23
0
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]]))

You had a problem with parenthesis at the print command.... This solution will be good now The correct solution in Visual Studio Code

McLovin
  • 555
  • 8
  • 20
0

I think this is what you are trying to do

def sum1(arr):
sum = 0
for i in range(len(arr)):
    for j in range(len(arr[0])):
        sum += arr[i][j]
return sum

print(sum1([[1, 2], [3, 4], [5, 6]]))
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 20 '23 at 12:20