How to add elements from a list and return the result as an integer?

6

I need to set the function soma_elementos

This function receives a list with integers and returns an integer corresponding to the sum of the elements of the list received. How do I do this?

def soma_elementos(lista):
    l = []
    
asked by anonymous 28.04.2017 / 08:24

2 answers

8

If this is not an exercise for learning, do not reinvent the wheel. Use the sum function, which serves just that.

soma = sum([1, 2, 3])
> 6

If you need to redo the sum function, try the following:

def somar_elementos(lista):
  soma = 0
  for numero in lista:
    soma += numero
  return soma
    
28.04.2017 / 08:47
-2

It is the sum of all elements of the list, is not it?

Try this:

soma = 0
for i in range(len(l)):
    soma += l[i]
print(soma)

Looking like this:

def soma_elementos(lista):
    l = lista
    return l

l = soma_elementos([1,2,3])
soma = 0
for i in range(len(l)):
    soma += l[i]
print(soma)
    
28.04.2017 / 08:31