# Python – Summation of consecutive elements power

PythonServer Side ProgrammingProgramming

When it is required to add the consecutive elements power, an ‘if’ condition and a simple iteration along with the ‘**’ operator are used.

## Example

Below is a demonstration of the same

my_list = [21, 21, 23, 23, 45, 45, 45, 56, 56, 67]

print("The list is :")
print(my_list)

my_freq = 1
my_result = 0

for index in range(0, len(my_list) - 1):

if my_list[index] != my_list[index + 1]:
my_result = my_result + my_list[index] ** my_freq
my_freq = 1

else:
my_freq += 1

my_result = my_result + my_list[len(my_list) - 1] ** my_freq

print("The resultant value is :")
print(my_result)

## Output

The list is :
[21, 21, 23, 23, 45, 45, 45, 56, 56, 67]
The resultant value is :
95298

## Explanation

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

• An integer for frequency and result are defined.

• The list is iterated over, and an ‘if’ condition is placed.

• It checks to see if consecutive elements are equal or not.

• If they are equal, the element is multiplied with its frequency and added to the result variable.

• The frequency variable is re-initialized to 1.

• Otherwise, the frequency variable is incremented by 1.

• This result variable is the output that is displayed on the console.

Published on 20-Sep-2021 08:55:36