Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to Mark duplicate elements in string
When it is required to mark duplicate elements in a string, list comprehension along with the count method is used. This technique helps identify repeated elements by appending occurrence numbers to duplicates.
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']
How It Works
The solution uses list comprehension with the following logic:
- For each element, check if its total count in the list is greater than 1
- If it's a duplicate, append the occurrence number (count up to current index + 1)
- If it's unique, keep the original value unchanged
- The
enumerate()function provides both index and value for each element
Alternative Approach Using Dictionary
Here's another method that tracks occurrences using a dictionary −
my_list = ["python", "is", "fun", "python", "is", "fun", "python", "fun"]
print("The list is :")
print(my_list)
seen = {}
result = []
for item in my_list:
if item in seen:
seen[item] += 1
result.append(item + str(seen[item]))
else:
seen[item] = 1
# Check if this item appears again later in the list
if my_list.count(item) > 1:
result.append(item + str(seen[item]))
else:
result.append(item)
print("The result is :")
print(result)
The list is : ['python', 'is', 'fun', 'python', 'is', 'fun', 'python', 'fun'] The result is : ['python1', 'is1', 'fun1', 'python2', 'is2', 'fun2', 'python3', 'fun3']
Conclusion
Both methods effectively mark duplicate elements by appending occurrence numbers. The list comprehension approach is more concise, while the dictionary method provides better readability and understanding of the logic flow.
Advertisements
