Python – Double each consecutive duplicate

Sometimes, while working with data, we can have a problem in which we need to perform double of element on each consecutive occurrence of a duplicate. This is very specific problem, but solution to this can prove to be very handy. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop
This is brute force way to perform this task. In this, we iterate each element and when we find duplicate we store in dictionary and perform its double subsequently.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Double each consecutive duplicate
# using loop
  
# Initializing list
test_list = [1, 2, 4, 2, 4, 1, 2]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Double each consecutive duplicate
# using loop
temp = {}
res = []
for ele in test_list:
    temp[ele] = temp1 = temp.get(ele, 0) + ele
    res.append(temp1)
      
# printing result 
print ("The list after manipulation is : " + str(res))

chevron_right


Output :

The original list is : [1, 2, 4, 2, 4, 1, 2]
The list after manipulation is : [1, 2, 4, 4, 8, 2, 6]

 

Method #2 : Using defaultdict() + loop
This method performs this task in similar way as above. The only difference is a step is reduced by using defaultdict() as it pre initializes the list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Double each consecutive duplicate
# using loop + defaultdict()
from collections import defaultdict
  
# Initializing list
test_list = [1, 2, 4, 2, 4, 1, 2]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Double each consecutive duplicate
# using loop + defaultdict()
temp = defaultdict(int)
res = []
for ele in test_list:
    temp[ele] += ele
    res.append(temp[ele])
      
# printing result 
print ("The list after manipulation is : " + str(res))

chevron_right


Output :

The original list is : [1, 2, 4, 2, 4, 1, 2]
The list after manipulation is : [1, 2, 4, 4, 8, 2, 6]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.