Python program for sum of consecutive numbers with overlapping in lists

PythonServer Side ProgrammingProgramming

When it is required to sum the consecutive numbers with overlapping elements in lists, a list comprehension, list slicing, concatenation operator and ‘zip’ methods are used.

Example

Below is a demonstration of the same −

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]

Explanation

• A list of integers is defined and is displayed on the console.

• A list comprehension is used to iterate over the elements.

• The ‘zip’ method is used to obtain specific indices of the list and concatenate them using the ‘+’ operator.

• This result is converted to a list and is assigned to a variable.

• This variable is displayed as output on the console.

Published on 08-Sep-2021 07:13:31