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 Append to a File
Python Program to Merge Two Dictionaries
Python Get Current time
Python String endswith()
Ways to Iterate Over a List in Java
Python Operator Overloading
Python all()
Python complex()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program to Create Pyramid Patterns
Python String isnumeric()
Python String splitlines()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Convert a Map to an Array, List or Set in Java
Python Set isdisjoint()
Python Objects and Classes
How to Get Started With Python?
Python Program to Slice Lists
Python Program to Count the Number of Each Vowel
Python Program to Differentiate Between type() and isinstance()
Python __import__()
Python strftime()
Python List append()
Python Program to Print Output Without a Newline
Python open()
Python Matrices and NumPy Arrays
Python String startswith()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python frozenset()
Python Program to Find the Square Root
Python Type Conversion and Type Casting
Python Program to Iterate Over Dictionaries Using for Loop