Table of Contents
In this example, you will learn to remove duplicate elements from a list.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Using set()
list_1 = [1, 2, 1, 4, 6] print(list(set(list_1)))
Output
[1, 2, 4, 6]
In the above example, we first convert the list into a set, then we again convert it into a list. Set cannot have a duplicate item in it, so set() keeps only an instance of the item.
2. Example 2: Remove the items that are duplicated in two lists
list_1 = [1, 2, 1, 4, 6] list_2 = [7, 8, 2, 1] print(list(set(list_1) ^ set(list_2)))
Output
[4, 6, 7, 8]
In the above example, the items that are present in both lists are removed.
- Firstly, both lists are converted to two sets to remove the duplicate items from each list.
- Then,
^gets the symmetric difference of two lists (excludes the overlapping elements of two sets).
Related posts:
Python for Loop
Python Exception Handling Using try, except and finally statement
Python vars()
Python Set symmetric_difference_update()
Python property()
Python Program to Check If a List is Empty
Python String capitalize()
Converting a List to String in Java
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Namespace and Scope
Python compile()
Python open()
Python complex()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Input, Output and Import
Python pow()
Python String rjust()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Global, Local and Nonlocal variables
Python type()
Python list()
Python Program to Check if a Number is Positive, Negative or 0
Python String count()
Python String isprintable()
Python List copy()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python Shallow Copy and Deep Copy
Python List count()
Python Tuple count()
Python divmod()
Python Program to Randomly Select an Element From the List
Python Program to Swap Two Variables