Python Program to remove the duplicate elements from a list


February 23, 2022, Learn eTutorial
944

In this simple python program, we need to remove the duplicate element. It is a number-based python program.

For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:

How to remove duplicate elements in python?

In this simple python program, we need to check the duplicate elements in a list and remove them. This means if any element which is repeated in the list must be removed from the list. For example, let us take a list of values [ 1, 2, 3, 4, 3, 5], then we have to remove the 3, which is repeating again. Then the result will be [1, 2, 3, 4, 5].

To apply this logic in python programming, we are initializing a list and get the number of terms from the user and append all the elements from the user using a for loop and append operator. Then we use the set() function to make a sequence of iterative values of set a to set b.I initialize another set for only unique elements, then open a for loop for all the elements in the list to check if any duplicate is found for that element in the set b. If not, any found, to add that element into the unique set using the append operator. then print the unique set.

ALGORITHM

STEP 1: Initialize the list for adding the elements from the user using python programming.

STEP 2: Accept the number of terms needed from the user and save that to a variable using input and int in python.

STEP 3: Open a for loop to append the user input elements to the list.

STEP 4: Using the set the built-in function makes the sequence of iterative elements in another set [copy of original set].

STEP 5: Initialize the third set for saving the unique elements from the original set.

STEP 6: Open a for loop to take each element from the original list to compare.

STEP 7: Compare the element with the elements in the list b. using if condition in the python programming language.

STEP 8: Add the unique elements to our third list and display the list of unique elements using print statements in python.

Python Source Code

                                          a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
    element=int(input("Enter element:"))
    a.append(element)
b = set()
unique = []
for x in a:
    if x not in b:
        unique.append(x)
        b.add(x)
print("Non-duplicate items:")
print(unique)
                                      

OUTPUT

Enter the number of elements in list:5
Enter element:10
Enter element:5
Enter element:7
Enter element:20
Enter element:20
Non-duplicate items:
[10, 5, 7, 20]