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

Sum of a list 2 elements by 2 elements

I have a 25 elements list like

tab=[6, 5, 5, 6, 3, 3, 2, 3, 2, 5, 6, 3, 2, 4, 5, 6, 4, 2, 1, 3, 1, 1, 4, 1, 5]

And I want to create a new list tab1 which display the sum of the elements of the list two by two, if the list is odd I don’t have to calculate the sum on the last element.
And it has to be done with a for loop for… any ideas?
Any help would be appreciated.
I tried on my side but without success.

i tried this :

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 tab:
print(sum(i:len(tab))

it gives me a syntax error and i tried some of others things but didn’t work…

i tried this too

for i in tab:
print(sum(i,i+1))

didn’t work too

and when i do this

sum=0
for i in tab:
print(sum(tab[i]+tab[i+1]))

it gives me back : TypeError: ‘int’ object is not callable

>Solution :

You could iterate over the list with steps of 2.

orig_len = len(tab)  # List length
tab1 = []
for i in range(0, orig_len - orig_len%2, 2):
  tab1.append(tab[i] + tab[i+1])
print(tab1)

You have to round down the number to first smaller even number, which is that orig_len - orig_len%2 does.

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