Given a list containing string, your task is to remove the duplicate elements present in the list of Strings. suppose if the list element occurs two times you should remove the second element and manage to retain only one element in the list.
Let's try to solve this using the Python program.
Write A Python Script To Delete Duplicate Strings From A List Of Strings
For any programming language you need an input to this program is a list of Strings so let's declare the list of things below into our Python program.
list_strings = ['Write', 'A', 'Python', 'Script', 'To', 'Delete', 'Duplicate', 'Strings', 'From', 'A', 'List', 'Of', 'Strings']
Now using the for loop enumerate all the items present in the list of string, enumerate functions will give us the index as well as the list item.
Use the index item and its index as a reference, use the while loop to iterate all the elements present in the list and check if index items exist in the list. If the index element exists then delete the element and continue.
for index, item in enumerate(list_strings):
index2 = index + 1
while index2 < len(list_strings):
if item == list_strings[index2]:
del list_strings[index2]
continue
index2 = index2 + 1
Once the for loop exits, the list will be having unique elements
present in the list of strings. now use print statements to print the list of strings.
print("List of Strings after deleting Duplicate Elements is : ")
print(list_strings)
Python Script
=====================
list_strings = ['Write', 'A', 'Python', 'Script', 'To', 'Delete', 'Duplicate', 'Strings', 'From', 'A', 'List', 'Of', 'Strings']
for index, item in enumerate(list_strings):
index2 = index + 1
while index2 < len(list_strings):
if item == list_strings[index2]:
del list_strings[index2]
continue
index2 = index2 + 1
print("List of Strings after deleting Duplicate Elements is : ")
print(list_strings)
Output
===============
List of Strings after deleting Duplicate Elements is :
['Write', 'A', 'Python', 'Script', 'To', 'Delete', 'Duplicate', 'Strings', 'From', 'List', 'Of']
Conclusion
==================
Modify the input value that you provide to the program that is a list of strings and execute the above Python program, note down the results.
Comment it down below if you have any queries related to the above Python program.
0 Comments