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

Asked

Viewed 49,622 times

9

I need to define the function soma_elementos

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

def soma_elementos(lista):
    l = []

7 answers

19

If this is not a learning exercise, don’t re-invent the wheel. Use the function sum, which is exactly what it’s for.

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

If you really need to redo the sum function, try this way:

def somar_elementos(lista):
  soma = 0
  for numero in lista:
    soma += numero
  return soma
  • I hadn’t learned about the sum function yet, but it worked out, thank you!

  • Not at all. Good studies.

0

Here’s the hint:

lista=[1,4,10]

def soma(lista): #  somatorio de varios numeros de uma lista com for
    num=0
    for c in lista:
        num+=c
    print(num)

You can exchange the ending for return depending on what you want to do

  • 2

    But they no longer answered that in the other answers?

0

as our friend @Antony Gabriel reported, should be a more didactic and not so functional question,

to sum all elements of a vector the first step is to go through all elements a 'n' ways of doing but I point out to you for var in vetor

in other words for each of the vetor travelling from start to finish, var will receive that value or be

for i in [1,4,3,6]:
   print(i)
  • i worth 1
  • i vale 4
  • i vale 3
  • i vale 6

you have already understood how to go through the vector the second step is to store the values by which you go through then out of the for there must be a variable that starts with 0 and when you go through each element you add this value to the variable

total = 0

for i in [1,4,3,6]:
   total = total + i
  • total = 1 as it is (0+1)
  • total = 5 as it is (1+4)
  • total = 8 as it is (5+3)
  • total = 14 as (8+6)

the last step is to throw everything into a function and observing the requests it has to receive a list and return the number of the sum of all elements soon will be like this?

def soma_elementos(lista):
    total = 0
    for i in lista:
       total = total + i
    return total

-1

Like Pablo mentioned, using the built-in sum(sua_lista) will add the vector efficiently and simply.

However, what many people do not know is that using the sum method of numpy library ( numpy.sum(sua_lista) ) will produce faster results if Voce uses a list with many elements instead of vector.

In the case of a list, just convert it to numpy array, or Voce can simply start its list as numpy array, add the elements and use the above function I mentioned.

More details about what I said can be observed in this post of the OS in English: https://stackoverflow.com/questions/10922231/pythons-sum-vs-numpys-numpy-sum/10922478

-2

It’s the sum of all the elements on the list, it’s not?

Try this:

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

Thus remaining:

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)
  • It didn’t work, it doesn’t work

  • Really? Here I tried and it worked, says the mistake that came there.

  • is because in the answer of always zero, I have to define the soma_elements, so when I open soma_elements([1,2,4]) for example, the result is 0, should be 7, right?

  • I’ll edit my answer and you try again.

  • Antony in reality your function soma_elementos is not doing anything, just receive and return the same, you can remove it and go through the list on the go as your first ex

  • I just put the function he created, it really doesn’t do anything, it depends on what Roberto will do.

Show 1 more comment

-2

def soma_elementos(lista):
    l = lista
    soma = 0
    for i in range(len(l)):
        soma += l[i]
    return soma

l = []
while True:
    x = int(input('Numero: '))
    if x == 0:
        break
    l.append(x)

l = soma_elementos(l)
print (l)
  • It works, but I recommend studying Pablo’s response to a more idiomatic solution.

-3

Not this wrong,... the question is that the FUNCTION returns l, which is a list and the screen prints the result of the sum,.... when in fact what you want is for the function to return the result of the sum!

See the following and implement!

#_________________________________
#Definindo a função
def soma_elementos(lista):
    l = lista
    soma = 0 #iniciando a variavel soma
    for i in range(len(l)): #variacao de i de acordo com o tamanho de l
    soma += l[i] #soma dos elemenos relacionados ao indice i do laço for
return soma #retorno de funçao
#_________________________________

l = soma_elementos([1,2,3,1,3,2])
print (l) o código aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.