
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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)
The given task is to perform an alternate summation on a Python List. For example, adding the elements at even indices (0, 2, 4) or odd indices (1, 3, 5), depending on the requirement. This means we need to add every other element from the given list.
Let us see an input scenario -
ScenarioInput: [11,22,33,44,55] Output: 99 Explanation: Here, we are going to add the elements at the even indices by using the slicing [::2].
Alternate Element Summation Using sum() Function
The alternate element summation in a list (Python) can be done by using the list slicing along with the built-in sum() function. The sum() function is used to calculate the sum of the elements from the sliced list, where slicing is used to pick every alternate element.
Syntax
Following is the syntax of the Python sum() function -
sum(iterable, start)
Slicing for Alternate Elements
- lst[::2] picks elements at the even indices (0, 2, 4.....) starting from index 0.
- lst[1::2] picks elements at the odd indices (1, 3, 5....) starting from index 1.
Example: Sum of Elements at Even Indices
Let's look at the following example, where we are going to sum the elements at even indices.
list = [11,22,33,44,55,66] alternate_list = list[::2] result = sum(alternate_list) print("Result :", result)
The output of the above program is as follows -
Result : 99
Example: Sum of elements at odd Indices
Consider another example, where we are going to sum the elements at odd indices -
lst = [2,4,6,8,10,12,14] result = sum(lst[1::2]) print("Result :", result)
Following is the output of the above program -
Result : 24
Example: Sum of Elements from the End
In the following example, we are going to sum the alternate elements from the end of the list -
lst = [3,6,9,12,15,18] result = sum(lst[::-2]) print("Result :", result)
If we run the above program, it will generate the following output -
Result : 36
Alternate Element Summation Using a For Loop
The alternate element summation in a list (Python) can be achieved by using a for loop with the range() function that starts at index 0 and skips every second element by specifying the step value 2 in the range() function.
Example
Following is the example we are going to use a for loop along with the range and add the alternate elements starting from index 0.
lst = [4,8,12,16,20] result = 0 for i in range(0, len(lst), 2): result += lst[i] print("Result :", result)
Following is the output of the above program -
Result : 36