Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program for sum of consecutive numbers with overlapping in lists
When summing consecutive numbers with overlapping elements in lists, we create pairs of adjacent elements where each element (except the last) is paired with its next neighbor. The last element pairs with the first element to create a circular pattern.
Example
Below is a demonstration using list comprehension with zip ?
my_list = [41, 27, 53, 12, 29, 32, 16]
print("The list is :")
print(my_list)
my_result = [a + b for a, b in zip(my_list, my_list[1:] + [my_list[0]])]
print("The result is :")
print(my_result)
Output
The list is : [41, 27, 53, 12, 29, 32, 16] The result is : [68, 80, 65, 41, 61, 48, 57]
How It Works
The algorithm creates overlapping pairs by combining the original list with a shifted version ?
numbers = [10, 20, 30, 40]
# Original list: [10, 20, 30, 40]
# Shifted list: [20, 30, 40, 10]
# Pairs: (10,20), (20,30), (30,40), (40,10)
shifted = numbers[1:] + [numbers[0]]
print("Original:", numbers)
print("Shifted: ", shifted)
result = [a + b for a, b in zip(numbers, shifted)]
print("Sums: ", result)
Original: [10, 20, 30, 40] Shifted: [20, 30, 40, 10] Sums: [30, 50, 70, 50]
Alternative Method Using Index
You can also achieve the same result using index manipulation ?
data = [5, 15, 25, 35]
result = []
for i in range(len(data)):
next_index = (i + 1) % len(data) # Wrap to 0 for last element
result.append(data[i] + data[next_index])
print("Input: ", data)
print("Output:", result)
Input: [5, 15, 25, 35] Output: [20, 40, 60, 40]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List comprehension + zip | High | Fast | Pythonic solution |
| Index with modulo | Medium | Slower | Understanding logic |
Conclusion
The zip method with list slicing provides an elegant solution for summing consecutive overlapping elements. The last element automatically pairs with the first, creating a circular summation pattern.
Advertisements
