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.
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']
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course