Skip to content
Related Articles

Related Articles

Python – Replace identical consecutive elements in list with product of the frequency and Item

View Discussion
Improve Article
Save Article
  • Last Updated : 19 Jan, 2022

Given a list, the task is to write a Python program to replace the grouping of the consecutive elements with a product of the frequency and Item.

Input : test_list = [3, 3, 3, 3, 6, 7, 5, 5, 5, 8, 8, 6, 6, 6, 6, 6, 1, 1, 1, 2, 2]

Output : [12, 6, 7, 15, 16, 30, 3, 4]

Explanation : 3 occurs 4 times in consecution hence, 3*4 = 12, the result.

Input : test_list = [3, 3, 3, 3, 6, 7, 5, 5, 5]

Output : [12, 6, 7, 15]

Explanation : 5 occurs 3 times in consecution hence, 5*3 = 15, the result.

Method 1: Using loop.

In this, the element is compared with the previous element for the decision of group end, if elements are different, a product of count till now and element is append as result. 

Python3




# Python3 code to demonstrate working of
# Equal Consecution Product
# Using loop
 
# initializing list
test_list = [3, 3, 3, 3, 6, 7, 5, 5, 5, 8,
             8, 6, 6, 6, 6, 6, 1, 1, 1, 2, 2]
              
# printing original list
print("The original list is : " + str(test_list))
 
res = []
count = 1
for idx in range(1, len(test_list)):
     
    # checking with prev element
    if test_list[idx - 1] != test_list[idx]:
         
        # appending product
        res.append((test_list[idx - 1] * count))
        count = 0
    count += 1
res.append((test_list[-1] * count))
 
# printing result
print("Elements after equal Consecution product : " + str(res))

Output:

The original list is : [3, 3, 3, 3, 6, 7, 5, 5, 5, 8, 8, 6, 6, 6, 6, 6, 1, 1, 1, 2, 2]

Elements after equal Consecution product : [12, 6, 7, 15, 16, 30, 3, 4]

Method 2: Using groupby() + sum()

In this, groups are formed using groupby() and summation of the grouped elements gives the required product.

Python3




# Python3 code to demonstrate working of
# Equal Consecution Product
# Using groupby() + sum()
from itertools import groupby
 
# initializing list
test_list = [3, 3, 3, 3, 6, 7, 5, 5, 5, 8, 8, 6, 6, 6, 6, 6, 1, 1, 1, 2, 2]
              
# printing original list
print("The original list is : " + str(test_list))
 
# creating Consecution groups and summing for required values
res = [sum(group) for k, group in groupby(test_list)]
 
# printing result
print("Elements after equal Consecution product : " + str(res))

Output:

The original list is : [3, 3, 3, 3, 6, 7, 5, 5, 5, 8, 8, 6, 6, 6, 6, 6, 1, 1, 1, 2, 2]

Elements after equal Consecution product : [12, 6, 7, 15, 16, 30, 3, 4]


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!