You can use list comprehension:
matrix = [[1, 2, 3], [4, 5, 6]]
sums = sum(y for x in matrix for y in x)
print sums
This runs as:
>>> matrix = [[1, 2, 3], [4, 5, 6]]
>>> sums = sum(y for x in matrix for y in x)
>>> print sums
21
>>>
Or you could use a basic for
loop:
matrix = [[1, 2, 3], [4, 5, 6]]
sums = 0
for sub in matrix:
for value in sub:
sums+=value
print sums
This runs as:
>>> matrix = [[1, 2, 3], [4, 5, 6]]
>>> sums = 0
>>> for sub in matrix:
... for value in sub:
... sums+=value
...
>>> print sums
21
>>>
List comprehension is the same as the double for
loops, only in one line:
Explanation of the following:
sums = sum(y for x in matrix for y in x)
Let's start at the beginning:
We use the builtin function sum()
to calculate all the values in the list:
>>> sum([1, 2, 3, 4]) #Should be 10
10
>>>
However, sum()
only works with flattened lists:
>>> sum([[1, 2], [3, 4]])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>>
Thus, we need to flatten it with double for
loops:
sum(y for x in matrix for y in x)
The for x in matrix
is basically taking every value of matrix, essentially [1, 2, 3]
and [4, 5, 6]
in this case. The for y in x
is assigning y to every value of x
, [1, 2, 3, 4, 5, 6]
. This is our flattened out list. Then we call sum()
, and everything works like magic!