Python – Replace all repeated occurrences with N

Sometimes, while working with Python list, we can have a problem in which we need to replace an element with another. But one can have variations of these such as increase of number and keeping the first occurrence. This can have applications in various domains. Lets discuss certain ways in which this task can be performed.

Method #1 : Using enumerate() + set() + loop
The combination of above functions can be used to perform this task. In this, we iterate the list and then store the 1st occurrence in set, the consecutive values are tested using in and replaced inplace.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Replace all repeated occurrences of K with N
# using enumerate() + set() + loop
  
# Initializing list
test_list = [1, 3, 3, 1, 4, 4, 1, 5, 5]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing N 
N = 'rep'
  
# Replace all repeated occurrences of K with N
# using enumerate() + set() + loop
his = set([])
for idx, ele in enumerate(test_list):
    if ele in his:
        test_list[idx] = N
    his.add(ele)
  
# printing result 
print ("The duplication altered list : " + str(test_list))

chevron_right


Output :

The original list is : [1, 3, 3, 1, 4, 4, 1, 5, 5]
The duplication altered list : [1, 3, 'rep', 'rep', 4, 'rep', 'rep', 5, 'rep']
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.