lista = [[1,2,3],[4,5,6],[7,8,9]]
print(lista)
def filas(lista):
res=[]
for elemento in lista:
x = sum(lista[elemento])
res.append(x)
print(res)
I need to sum the numbers of each row, and then print it as a list. It seems the problem I have is that I try to sum the sublists, instead of the numbers of each row.
The issue you are having, is that you are already iterating over the elements so it is unnecessary to use it as an index:
x = sum(elemento)
It is generally considered bad form but to iterate over indexes you would use:
for i in range(len(lista)):
x = sum(lista[i])
However, without introducing any other modules, you can use map()
or a simple list comprehension:
>>> res = list(map(sum, lista)) # You don't need `list()` in Py2
>>> print(res)
[6, 15, 24]
Or
>>> res = [sum(e) for e in lista]
>>> print(res)
[6, 15, 24]
Do you want like this?
lista = [[1,2,3],[4,5,6],[7,8,9]]
print(lista)
def filas(lista):
summed_list = [sum(i) for i in lista]
print(summed_list)
filas(lista)
Is this what you want to do?
def filas(lista):
res=[]
for elemento in lista:
x = sum(elemento) # <- change this line.
res.append(x)
print(res)