I think this is better:
>>> x=[[1, 2],[3, 4],[5, 6]]
>>> sum(sum(x,[]))
21
Answer from hit9 on Stack OverflowI think this is better:
>>> x=[[1, 2],[3, 4],[5, 6]]
>>> sum(sum(x,[]))
21
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
state=[[3,2,3],[23,4,4],[5,43,3]] s=sum(state, [])
This code transforms a 2D array to 1D array (all elements of the 2D array are now elements of an 1D array). I know that sum() first parameter sums all the elements of the iterable and the second is the starting point. But i really dont get how this leads to 2D--->1D
python - How is Numpy sum adding up elements of a 2d array? - Stack Overflow
How to sum rows and columns in a 2d list?
If you want to do this without numpy:
sum_rows = [sum(x) for x in values] sum_cols = [sum(x) for x in zip(*values)]
For larger arrays, numpy.sum is the way to go.
How to produce the sum of two 2D lists by element?
python - How to calculate the sum of all columns of a 2D numpy array (efficiently) - Stack Overflow
I am trying to figure out how to sum each individual row, and then each column. Here is what I have so far:
import random
rows = 3
cols = 3
def main():
values = [[0,0,0], [0,0,0], [0,0,0]]
for r in range(rows):
for c in range(cols):
values[r][c] = random.randint(1, 4)
print('List')
print(values)main()
If you want to do this without numpy:
sum_rows = [sum(x) for x in values]
sum_cols = [sum(x) for x in zip(*values)]
For larger arrays, numpy.sum is the way to go.
The other 2 answers have covered it, but for the sake of clarity, remember that 2D lists don't exist. That is a list of lists, and thinking about it that way should have helped you come to a solution. It's always worth being very specific in your own mind about different types (for example, the difference between a 2D array and a matrix in numpy, or the difference between a list and a numpy array) because colloquially referring to a type as something it's not will often give you faulty assumptions how it ought to work.
As an example, if I have two lists
list1 = [[1,2], [3,4]] list2 = [[5,6], [7,8]]
I'd like a third list to be
list3 = [[6,8], [10,12]]
I know that for a single dimensional list I would just use the syntax
newList = [sum(x) for x in zip(oldList1, oldList2)]
but I can't for the life of me figure out how to apply this to a 2D list.
What would be the most Pythonic way of doing this? I've tried fiddling with for loops but I got nowhere and I figure that it's not the best way to get it done anyway.
Thanks in advance!
EDIT: Formatting
Check out the documentation for numpy.sum, paying particular attention to the axis parameter. To sum over columns:
>>> import numpy as np
>>> a = np.arange(12).reshape(4,3)
>>> a.sum(axis=0)
array([18, 22, 26])
Or, to sum over rows:
>>> a.sum(axis=1)
array([ 3, 12, 21, 30])
Other aggregate functions, like numpy.mean, numpy.cumsum and numpy.std, e.g., also take the axis parameter.
From the Tentative Numpy Tutorial:
Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the
ndarrayclass. By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying theaxisparameter you can apply an operation along the specified axis of an array:
Other alternatives for summing the columns are
numpy.einsum('ij->j', a)
and
numpy.dot(a.T, numpy.ones(a.shape[0]))
If the number of rows and columns is in the same order of magnitude, all of the possibilities are roughly equally fast:

If there are only a few columns, however, both the einsum and the dot solution significantly outperform numpy's sum (note the log-scale):

Code to reproduce the plots:
import numpy
import perfplot
def numpy_sum(a):
return numpy.sum(a, axis=1)
def einsum(a):
return numpy.einsum('ij->i', a)
def dot_ones(a):
return numpy.dot(a, numpy.ones(a.shape[1]))
perfplot.save(
"out1.png",
# setup=lambda n: numpy.random.rand(n, n),
setup=lambda n: numpy.random.rand(n, 3),
n_range=[2**k for k in range(15)],
kernels=[numpy_sum, einsum, dot_ones],
logx=True,
logy=True,
xlabel='len(a)',
)