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:
Debug a JavaMail Program
Python Objects and Classes
Python String rpartition()
Converting between an Array and a List in Java
Python Program Read a File Line by Line Into a List
Python String split()
Python Program to Print Output Without a Newline
Python Program to Compute the Power of a Number
Python issubclass()
Python Program to Merge Two Dictionaries
Python Operators
Python Program to Find HCF or GCD
Python Program to Capitalize the First Character of a String
Python Namespace and Scope
Python Dictionary values()
Python Input, Output and Import
Python Machine Learning - Sebastian Raschka
Python Decorators
Python String join()
Python Program to Print all Prime Numbers in an Interval
Python Set pop()
Python Program to Make a Flattened List from Nested List
Python String expandtabs()
Python Program to Check Whether a String is Palindrome or Not
Python Object Oriented Programming
Python Program to Check if a Key is Already Present in a Dictionary
Python break and continue
Python Program to Get a Substring of a String
Python Program to Find LCM
Python String encode()
Python setattr()
Python staticmethod()