You can use two for
nested, the first iterates over the rows and the second over the elements of each row and use a variable to store the sum as you comment:
suma = 0
for fila in matriz:
for n in fila:
suma += n
However using the built-in sum
is more efficient, in order to apply it one possibility is to flatten the list first and then apply sum
. In addition to the forms that @Ale shows in its response we can use itertools.chain.from_iterable
>>> import itertools
>>> matriz = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> sum(itertools.chain.from_iterable(matriz))
45
The second thing that you propose is not more than an accumulated sum, for it itertools
also has the solution, itertools.accumulate
:
>>> cumsum = list(itertools.accumulate(itertools.chain.from_iterable(matriz)))
>>> cumsum
[1, 3, 6, 10, 15, 21, 28, 36, 45]
The normal thing is to use a list or other iterable one to store the accumulated sums, but if you want to use 9 variables simply unpack:
>>> cumsum = itertools.accumulate(itertools.chain.from_iterable(matriz))
>>> var_1, var_2, var_3, var_4, var_5, var_6, var_7, var_8, var_9 = cumsum