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.

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.

Updated on: 15-Sep-2021

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements