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