12

The closest was this one summing columns.

So I'll do something similar in my question:

Say I've a Python 2D list as below:

my_list =  [ [1,2,3,4],
             [2,4,5,6] ]

I can get the row totals with a list comprehension:

row_totals = [ sum(x) for x in my_list ]

In one line, how can I sum the entire 2d-array?

27

5 Answers 5

20

You can do as easy as

sum(map(sum, my_list))

or alternatively

sum(sum(x) for x in my_list))

and call it a day, if you don't expect more than 2 dimensions. Note that the first solution is most likely not the fastest (as in execution time) solution, due to the usage of map(). Benchmark and compare as necessary.

Finally, if you find yourself using multidimensional arrays, consider using NumPy and its superior array-friendly functions. Here's a short excerpt for your problem:

import numpy as np

my_list = np.array([[1,2,3,4], [2,4,5,6]])
np.sum(my_list)

This would work for any number of dimensions your arrays might have.

Sign up to request clarification or add additional context in comments.

5 Comments

map is not inherently slow.
@katrielalex: The numbers disagree with you: ideone.com/4RXfR vs ideone.com/6tOEJ
@Marcin you're missing the point -- if you use a list comprehension then the advantage of map goes away. Otherwise it allocates an unnecessary list.
@katrielalex No, I don't think I am missing the point. In a fair comparison, map is faster. In fact, you can check those links again - I've updated them to use sum of map vs sum of generator expression.
youve got a typo in your solution
4

Another solution using itertools:

>>> from itertools import chain
>>> my_list = [ [1,2,3,4], [2,4,5,6] ]
>>> sum(chain(*my_list))
27

2 Comments

What does the * stands for?
It's the "unpacking operator" (* for lists/tuples, ** for dictionaries): docs.python.org/3/tutorial/…
3
>>> sum ( [ sum(x) for x in [[1,2,3,4], [2,4,5,6]] ] )
27

2 Comments

Use a generator not a list comprehension (() not []).
@katrielalex: you are right, as well as mindcorrosive. I took OP code to test, then forgot to remove squares.
1
>>> from itertools import chain
>>> my_list = [[1,2,3,4], [2,4,5,6]]
>>> sum(chain.from_iterable(my_list))
27

Comments

0

You can use sum to first add the inner lists together and then sum the resulting flattened list:

>>> my_list = [ [1,2,3,4], [2,4,5,6] ]

>>> sum(my_list, [])
[1, 2, 3, 4, 2, 4, 5, 6]

>>> sum(sum(my_list, []))
27

1 Comment

Does your answer add anything on top of the other answers here?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.