Given a list of numbers in this article we are going to calculate the sum of alternate elements in that list.
With list slicing and range
Every second number and also use the range function along with length function to get the number of elements to be summed.
Example
listA = [13,65,78,13,12,13,65] # printing original list print("Given list : " , str(listA)) # With list slicing res = [sum(listA[i:: 2]) for i in range(len(listA) // (len(listA) // 2))] # print result print("Sum of alternate elements in the list :\n ",res)
Output
Running the above code gives us the following result −
Given list : [13, 65, 78, 13, 12, 13, 65] Sum of alternate elements in the list : [168, 91]
With range and %
Use the percentage operator to separate the numbers at Even and Odd positions. And then add the elements to the respective position of a new empty list. Finally giving a list which shows sum of elements at odd position and sum of elements at even position.
Example
listA = [13,65,78,13,12,13,65] # printing original list print("Given list : " , str(listA)) res = [0, 0] for i in range(0, len(listA)): if(i % 2): res[1] += listA[i] else : res[0] += listA[i] # print result print("Sum of alternate elements in the list :\n ",res)
Output
Running the above code gives us the following result −
Given list : [13, 65, 78, 13, 12, 13, 65] Sum of alternate elements in the list : [168, 91]