

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- 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
- Alternate range slicing in list (Python)
- Python Grouped summation of tuple list¶
- Summation of list as tuple attribute in Python
- Python – Check alternate peak elements in List
- Python - List Initialization with alternate 0s and 1s
- List consisting of all the alternate elements in Python
- Alternate sorting of Linked list in C++
- Python - Column summation of tuples
- Python Alternate repr() implementation
- Element repetition in list in Python
Advertisements