Sum of list of lists; returns sum list
Asked Answered
J

11

43

Let data = [[3,7,2],[1,4,5],[9,8,7]]

Let's say I want to sum the elements for the indices of each list in the list, like adding numbers in a matrix column to get a single list. I am assuming that all lists in data are equal in length.

    print foo(data)

   [[3,7,2],
    [1,4,5],
    [9,8,7]]
    _______
 >>>[13,19,14]

How can I iterate over the list of lists without getting an index out of range error? Maybe lambda? Thanks!

Jurel answered 9/12, 2012 at 0:9 Comment(0)
B
87

You could try this:

In [9]: l = [[3,7,2],[1,4,5],[9,8,7]]

In [10]: [sum(i) for i in zip(*l)]
Out[10]: [13, 19, 14]

This uses a combination of zip and * to unpack the list and then zip the items according to their index. You then use a list comprehension to iterate through the groups of similar indices, summing them and returning in their 'original' position.

To hopefully make it a bit more clear, here is what happens when you iterate through zip(*l):

In [13]: for i in zip(*l):
   ....:     print i
   ....:     
   ....:     
(3, 1, 9)
(7, 4, 8)
(2, 5, 7)

In the case of lists that are of unequal length, you can use itertools.izip_longest with a fillvalue of 0 - this basically fills missing indices with 0, allowing you to sum all 'columns':

In [1]: import itertools

In [2]: l = [[3,7,2],[1,4],[9,8,7,10]]

In [3]: [sum(i) for i in itertools.izip_longest(*l, fillvalue=0)]
Out[3]: [13, 19, 9, 10]

In this case, here is what iterating over izip_longest would look like:

In [4]: for i in itertools.izip_longest(*l, fillvalue=0):
   ...:     print i
   ...:     
(3, 1, 9)
(7, 4, 8)
(2, 0, 7)
(0, 0, 10)
Brainy answered 9/12, 2012 at 0:18 Comment(6)
Or map(sum,zip(*l)) (this one's my favorite).Caret
@A.R.S. That's definitely a nice one - there's something about map I've always liked :)Brainy
this doesn't work if the list is of different sizes for eg l = [[3,7,2],[1,4],[9,8,7,10]] gives [13, 19]. using python3Improbability
@Improbability The OP needed something to work with equal-sized lists, but you make a good point :) I updated the answer to handle non-equal lists as well - let me know if that helps!Brainy
@Brainy your result is now 4 elements while your list has 3 sublist. See my post belowImprobability
@Improbability I believe we are solving two different problems :) The OP wanted a list where index position 1 was the sum of all of the first indices of the sublists, position 2 the sum of the second indices, etc. Therefore mine has four elements because the longest list has four items. Yours sums each sublist, so index 1 is the sum of sublist 1, etc. (unless I'm missing something).Brainy
U
17

For any matrix (or other ambitious numerical) operations I would recommend looking into NumPy.

The sample for solving the sum of an array along the axis shown in your question would be:

>>> from numpy import array
>>> data = array([[3,7,2],
...     [1,4,5],
...     [9,8,7]])
>>> from numpy import sum
>>> sum(data, 0)
array([13, 19, 14])

Here's numpy's documentation for its sum function: http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html#numpy.sum

Especially the second argument is interesting as it allows easily specify what should be summed up: all elements or only a specific axis of a potentially n-dimensional array(like).

Ulane answered 9/12, 2012 at 0:15 Comment(3)
Thanks for inquiring. I added a sample. I would think that this would be more time and space efficient than any of the other samples.Ulane
Appreciated - especially given that I never used Numpy before, but I know some guys who do scientific computing and use it extensively. I was surprised myself how easy this was.Ulane
Disclaimer- This will only work if all the sublists have same length.Centrality
I
12

This will give you the sum for each sublist

data = [[3,7,2],[1,4],[9,8,7,10]]
list(map(sum, data))
[12, 5, 34]

If you want to sum over all elements and get just one sum then use this

data = [[3,7,2],[1,4],[9,8,7,10]]
sum(sum(data, []))
51
Improbability answered 14/7, 2013 at 13:4 Comment(2)
You don't happen to be doing the Linear Algebra course on Coursera are you? Can you explain why the second one works?Essential
The result of sum([[1,2],[3,4]],[]) is [1, 2, 3, 4]. So, it is obvious that the extra argument to sum is telling it something about how to sum. Indeed, list + list in python just appends the lists. Then the second sum just sums the combined list. I will still prefer the map solution for performance, but this is simple and pythonic in a way.Criminology
S
2
>>> data = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> for column in enumerate(data[0]):
...     count = sum([x[column[0]] for x in data])
...     print 'Column %s: %d' % (column[0], count)
... 
Column 0: 3
Column 1: 6
Column 2: 9
Silures answered 9/12, 2012 at 0:17 Comment(0)
O
1
import numpy as np
l = [[3,7,2],[1,4,5],[9,8,7]]
print(sum(np.array(l)[:,:]))
print(sum(np.array(l)[:,0:2]))

#answer:
#[13 19 14]
#[13 19]
# use np like row column
Ogdoad answered 8/5, 2024 at 19:16 Comment(0)
G
0

This does depend on your assumption that all the inner lists (or rows) are of the same length, but it should do what you want:

sum_list = []

ncols = len(data[0])

for col in range(ncols):
    sum_list.append(sum(row[col] for row in data))


sum_list
Out[9]: [13, 19, 14]
Girder answered 9/12, 2012 at 0:15 Comment(0)
F
0
def sum(L):
res = list()
for j in range(0,len(L[0])):
    tmp = 0
    for i in range(0,len(L)):
        tmp = tmp + L[i][j]
    res.append(tmp)
return res
Footcandle answered 19/6, 2014 at 13:27 Comment(0)
M
0

This solution assumes a square matrix and uses two for loops to loop over the columns and rows, adding column-wise in the process. The result is returned in a list.

def foo(data):
    # initialise length of data(n) and sum_of_col variable 
    n = len(data)
    sum_of_col = []

    # iterate over column
    for col_i in range(n):
        # column sum
        col_count = 0;

        #iterate over row
        for row_i in range(n):
            col_count += data[row_i][col_i]

        # append sum of column to list    
        sum_of_col.append(col_count)

    return sum_of_col
Mullock answered 11/10, 2019 at 6:0 Comment(0)
A
0

The simplest solution that will sum a list of lists of different or identical lengths is:

total = 0
for d in data:
    total += sum(d)

Once you understand list comprehension you could shorten it:

sum([sum(d) for d in data])
Aundreaaunson answered 11/10, 2019 at 6:13 Comment(0)
M
0

For the case that the data is a list of lists of strings. Sum or concatenate a list of lists of strings elementwise.

>>> a = [list('abc'),list('def'),list('tyu')]
>>> a
[['a', 'b', 'c'], ['d', 'e', 'f'], ['t', 'y', 'u']]
>>> [''.join(thing) for thing in zip(*a)]
['adt', 'bey', 'cfu']
>>> 
Mauromaurois answered 5/1, 2020 at 18:4 Comment(0)
A
-1
numArr = [[12, 4], [1], [2, 3]]

sumArr = 0

sumArr = sum(sum(row) for row in numArr)

print(sumArr) 

the answere: 22

what I did: when you do "for" like this for example: [row.append(1) for row in numArr] the list will change to: [[12, 4, 1], [1, 1], [2, 3, 1]] I used the function sum() from python, the function takes the list and do iteration on it and bring the sum of all the numbers in the list. when I did sum(sum()) I got the sum of all the lists in the big list.

Arv answered 24/3, 2019 at 10:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.