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 chr()
Python String expandtabs()
Python Operator Overloading
Python String istitle()
Python Numbers, Type Conversion and Mathematics
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Program to Append to a File
Python Program to Find LCM
Python bin()
Removing all Nulls from a List in Java
Python Program to Iterate Through Two Lists in Parallel
Python String endswith()
Python Program to Get the Full Path of the Current Working Directory
Python hash()
How to get current date and time in Python?
Python issubclass()
Python Program to Find the Size (Resolution) of a Image
Java List UnsupportedOperationException
Convert a Map to an Array, List or Set in Java
Python Program to Convert Kilometers to Miles
Python Get Current time
Python callable()
Python str()
Python String center()
Python Program to Check if a Key is Already Present in a Dictionary
Python Program to Reverse a Number
Python Program to Split a List Into Evenly Sized Chunks
Intelligent Projects Using Python - Santanu Pattanayak
Python Program to Parse a String to a Float or Int
Python Iterators
Python int()
Python Program to Print the Fibonacci sequence