-1

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:
    x.remove(i)

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.

  • 2
    For adding, use [`sum`](https://docs.python.org/library/functions.html#sum). Applying subtraction to multiple values has no clear meaning. Can you provide an example and clarify the behaviour you expect? – ChrisGPT was on strike Apr 13 '23 at 13:24
  • `x.append(sum(x))` to start I think. As for removing items from a list while iterating over it, you will want to look at: https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating – JonSG Apr 13 '23 at 13:24
  • I should have clarified; for subtraction I meant an original value at the start of the array, and then subtract the rest of the array from that. – Hugo Thompson Apr 13 '23 at 13:33
  • 1
    Also Chris, I used range(len(x)) so that I could manipulate the next item as well (eg. x[i+1]) – Hugo Thompson Apr 13 '23 at 13:38
  • What do you mean with "this works"? The result is `[0, 22]`. Is that truly what it shall be? – Kelly Bundy Apr 13 '23 at 13:40
  • @Chris It's not `range(len(x))` but `range(len(x)-1)`. And they assign back into the list. Your `for num in x` doesn't achieve either. And their second loop is `for i in x:`, so they're already aware of that possibility. – Kelly Bundy Apr 13 '23 at 13:44
  • @HugoThompson So since you didn't specify what you want in text, and your code is likely wrong, we don't know what you actually want. – Kelly Bundy Apr 13 '23 at 13:48

2 Answers2

1

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:]).

bc1155
  • 263
  • 7
0

You can simply just use the sum function: sum(x).

TYZ
  • 8,466
  • 5
  • 29
  • 60