Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading