
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Mark Duplicate Elements in String using Python
When it is required to mark duplicate elements in a string, list comprehension along with the ‘count’ method is used.
Example
Below is a demonstration of the same
my_list = ["python", "is", "fun", "python", "is", "fun", "python", "fun"] print("The list is :") print(my_list) my_result = [value + str(my_list[:index].count(value) + 1) if my_list.count(value) > 1 else value for index, value in enumerate(my_list)] print("The result is :") print(my_result)
Output
The list is : ['python', 'is', 'fun', 'python', 'is', 'fun', 'python', 'fun'] The result is : ['python1', 'is1', 'fun1', 'python2', 'is2', 'fun2', 'python3', 'fun3']
Explanation
A list is defined and is displayed on the console.
The list comprehension is used to iterate through the values and check the count.
If the count of a specific value is greater than 1, the value is added to the element’s count.
Otherwise, it is enumerated over.
This is assigned to a variable.
It is the output that is displayed on the console.
Advertisements