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 Program to Extract Extension From the File Name
Python String swapcase()
Python max()
Python Program to Convert Decimal to Binary Using Recursion
Python String isprintable()
Python Program to Check If a List is Empty
Python Program to Delete an Element From a Dictionary
Python Set difference_update()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python memoryview()
Python Program to Calculate the Area of a Triangle
Python break and continue
Python Program to Differentiate Between del, remove, and pop on a List
Python Program to Check Whether a String is Palindrome or Not
Python List Comprehension
Python strftime()
Python len()
Python Directory and Files Management
Using a List of Values in a JdbcTemplate IN Clause
Python globals()
Python help()
Python *args and **kwargs
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python tuple()
Node.js vs Python for Backend Development
Python getattr()
Remove the First Element from a List
Python Program to Check if a Key is Already Present in a Dictionary
Python Inheritance
Python Program to Iterate Through Two Lists in Parallel
Python Dictionary popitem()
Python Program to Access Index of a List Using for Loop