Python program to remove duplicate items from a list :

In this tutorial, we will learn how to remove all duplicate items from a list and create a new list by removing all duplicate items.
The program will ask the user to enter the items from the list. It will then remove all duplicate elements from the list and print out the new list.
We will learn to solve this problem by using two different approaches.

Approach 1: Remove the duplicate items by using a separate list :

In this approach, we will remove the duplicate items of a list by creating a different list. At first, we will create one empty list. Then we will iterate through the original list and fill the new empty list without any duplicate element. For that, we will check in the new list if the current element has already existed or not.
Example python program : (Source code for the program is available here)

python remove all duplicates from list

Output :

python remove all duplicates from list

python remove duplicates from a list
As you can see, the original list was [1, 3, 5, 7, 2, 1, 5, 2, 8] and we have changed it to [1, 3, 5, 7, 2, 8]. All duplicate elements are removed from the list.

Explanation :

The commented numbers in the above program denote the step numbers below :

1. The original number list original_list. Our program will remove all duplicate items from this list. Print the list to the user at first.
2. Create one empty list final_list. We will add all elements of original_list to final_list excluding all duplicate elements.
3. Using one for loop, iterate through all items of original_list one by one.
4. Check for each element, if it is already in the final_list or not. If not, append the item to the list.
5. Finally, print the modified list.

Approach 2 : Using set() :

Instead of iterating through the list to remove all duplicate items, we can also convert the list to a set and then convert it back to a list.
Since a set can’t hold any duplicate elements, it will produce one list with unique items.

python remove all duplicate from list

Output :

python remove all duplicate from list

python remove duplicate from list

Explanation :

The commented numbers in the above program denote the step numbers below :

1. original_list is the given list.
2. Print out the list to the user.
3. Convert the list to a set using set() and then convert this set to a list using list(). This list will contain no duplicate elements.
4. Print out the list.

Conclusion :

Both ways we have seen above can be used to remove duplicate elements from a list. The only difference is that the first method keeps the order of the elements but the second method doesn’t keep the order.
Try to go through the programs and drop one comment below if you have any queries.

 

You might also like :

Categories: python

Leave a Reply

Your email address will not be published. Required fields are marked *