Hi Guys, welcome to my blog in this article you will learn about how to Write A Python Program To Remove Duplicates From A List
Title :
Write A Python Program To Remove Duplicates From A List
Description :
Hey Guys, In this article let me explain to you how to remove duplicate elements out of a python list data structure.
Lets accept a list from the user and get the list into the program, lets use list of numbers as example.
Then try to iterate all the elements of the list and then remove if they already existed in the list.
Finally print the list having unique elements.
length = int(input("Enter List Length : "))
my_list = []
for _ in range(length):
temp = int(input("Enter List Item : "))
my_list.append(temp)
Lets ask the user the enter list length, then use the for loop to iterate from 0 to list length, while we iterate keep asking user to enter the list element and append the item to list
for index, item in enumerate(my_list):
index2 = index + 1
while index2 < len(my_list):
if item == my_list[index2]:
del my_list[index2]
continue
index2 = index2 + 1
Use the for loop to iterate all the items present in the list and also get the index value by enumerating the list. Get the next indexed item and use the while loop to iterate from index2 until the list length and check if item is same as index2 item if so delete the item and continue to increment the index2 by 1. The reason we are using the len() function to check is when we delete an item from a list, list size reduces. Also, we will use the continue statement to check if subsequent items are the same as the current item.
Complete Python Code :
length = int(input("Enter List Length : "))
my_list = []
for _ in range(length):
temp = int(input("Enter List Item : "))
my_list.append(temp)
for index, item in enumerate(my_list):
index2 = index + 1
while index2 < len(my_list):
if item == my_list[index2]:
del my_list[index2]
continue
index2 = index2 + 1
print(my_list)
Output :
Enter List Length : 5
Enter List Item : 1
Enter List Item : 2
Enter List Item : 3
Enter List Item : 2
Enter List Item : 2
[1, 2, 3]
Output :
Enter List Length : 5
Enter List Item : 1
Enter List Item : 2
Enter List Item : 2
Enter List Item : 2
Enter List Item : 3
[1, 2, 3]
Conclusion :
In this blog, we discussed how to write a python program to remove duplicates from a list.
We are using the for loop to iterate and get the selected item from the list . We also use the while loop to check if the selected item is part of the remaining list so it can be deleted.
We keep deleting the list item to get unique values in the list and finally display the list.
0 Comments