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 divmod()
Python Data Structures and Algorithms - Benjamin Baka
Remove the First Element from a List
Python Set difference_update()
Python dict()
Python String rfind()
Python Package
Python String maketrans()
Python Program to Make a Simple Calculator
Python Program to Iterate Over Dictionaries Using for Loop
Python String join()
Python frozenset()
Python String islower()
Python Program to Get the Class Name of an Instance
Java Program to Implement the Program Used in grep/egrep/fgrep
Python Program to Add Two Numbers
Python Dictionary popitem()
Python hex()
Python List pop()
Python Dictionary pop()
Python Program to Calculate the Area of a Triangle
Python Program to Find Sum of Natural Numbers Using Recursion
Python Set intersection_update()
Python Generators
Python Program to Capitalize the First Character of a String
Node.js vs Python for Backend Development
Python Program to Illustrate Different Set Operations
Python List remove()
Python frozenset()
Python String center()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Find the Sum of Natural Numbers