How to subtract several elements from a list?

Asked

Viewed 773 times

2

I am making a calculator and would like to subtract several elements from a list, this because the list can have as many elements as the user wants. See my code:

lista = [10, 5]
subt = lista[0]
for a in lista:
  subt -= a

But the algorithm is giving me -5 as an answer, which should be 5 (10-5 = 5). It is worth mentioning again that the list can have as many elements as the user wants, be 2, 3, 4, 5, 100...

What a possible solution?

  • for a list like this 2, 3, 4, 5, 100 what you expect as a result ??

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site

2 answers

5

You’re taking the whole list, so the first subtraction is the element you’ve already taken, the first step of the loop will reset the value because a number minus it is always zero, then the account starts.

The solution is to take the first item there and then work only with the rest of the list. Python has a way to do this simply. You can use the ability to decompose multiple values into variables, then you have the first element in a variable and then to put all the remaining elements use the operator * (otherwise it would only take the second value, which actually works in this example, but would not work in larger lists). Something like this:

subt, *tail = [10, 5]
for a in tail:
    subt -= a
print(subt)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

See more in What is the meaning of the operator ( * ) asterisk? and Extended Iterable Unpacking.

2


As you want to subtract the first element from the others, an alternative is to do the loop from the second element:

subt = lista[0]
for a in lista[1:]:
    subt -= a

In the case, lista[1:] creates a sub-list containing the second element on ([1:] uses the syntax of slicing to pick from index 1 to the end of the list - if the list has only one element, the sub-list will be empty and will not enter the for).

This follows the same idea of another answer, I’m just creating the sub-list in a different way.


Another way to see the problem is to realize that you actually want to do:

primeiro_elemento - soma_dos_demais_elementos

Translating to Python would look like this:

subt = lista[0] - sum(lista[1:])

Browser other questions tagged

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