python

Python – Remove duplicates from a list

In this tutorial, we are going to see How to remove duplicates from a list in Python.
 
Example:
In the following example, we will take a list with duplicates elements and generate another list that contains only the elements without the duplicates.

Input: [1, 2, 3, 3, 2, 4, 5]
Output: [1, 2, 3, 4, 5]
 

Remove duplicates from a list using Set

Set is an unordered data structure that contains only unique elements.

# List of numbers containing duplicates
nbrList = [1, 2, 3, 3, 2, 4, 5]
# Convert list to set and set to list
nbrList = list(set(nbrList))
# Display the new list 
print(nbrList)

Output:

[1, 2, 3, 4, 5]

 

Remove duplicates from a list using “NOT IN” operator

We can apply the “NOT IN” operator on the list to find the duplicates. We create a new list and insert only those that are not already in.

nbrList  = [1, 2, 3, 3, 2, 4, 5]

new_list = [] 
for i in nbrList : 
    if i not in new_list: 
        new_list.append(i) 

print(new_list)

Output:

[1, 2, 3, 4, 5]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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