When it is required to mark duplicate elements in a string, list comprehension along with the ‘count’ method is used.
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)
The list is : ['python', 'is', 'fun', 'python', 'is', 'fun', 'python', 'fun'] The result is : ['python1', 'is1', 'fun1', 'python2', 'is2', 'fun2', 'python3', 'fun3']
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.