
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Alternate element summation in list (Python)
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]
- Related Articles
- Python – Dual Tuple Alternate summation
- Python - Increasing alternate element pattern in list
- Increasing alternate element pattern in list in Python
- Summation of tuples in list in Python
- Grouped summation of tuple list in Python
- Python Grouped summation of tuple list¶
- Alternate range slicing in list (Python)
- Summation of list as tuple attribute in Python
- Python – Check alternate peak elements in List
- List consisting of all the alternate elements in Python
- Python - List Initialization with alternate 0s and 1s
- Python Program to Alternate list elements as key-value pairs
- Alternate sorting of Linked list in C++
- Element repetition in list in Python
- Python - Column summation of tuples

Advertisements