How do I add or subtract all the items in an array of integers efficiently in python?


this question is less about a specific issue, and more about a problem that I continuously have while working with arrays.

Say I have an array like this:

x = [4,7,11]

If I wanted to add al of these together, what I would do is:

for i in range(len(x)-1):
  x[i+1] = x[i]+x[i+1]
  x[i] = 0

I would then follow this with:

for i in x:
  if i == 0:

Although this works, It’s incredibly slow and definitely not the most efficient way to do this, besides taking up several extra lines.

If anyone has a better way to do this, please tell me. This physically hurts me every time I do it.

>Solution :

As TYZ said, you can simply use sum(x) for getting the sum of a numerical list.

For subtraction where you subtract later items from the first item, you can use x[0]-sum(x[1:]).

Leave a ReplyCancel reply