

Remove duplicates from a list in Python
source link: https://dev.to/foxy4096/remove-duplicates-from-a-list-in-python-3oj5
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Remove duplicates from a list in Python
I am going straight to the point
my_list = [1, 2, 3, 4, 4, 5, 2]
How do we remove duplicate no. or elements from the list.
Simple, we have 3 easy method.
- Using
set
my_list = [1, 2, 3, 4, 4, 5, 2]
updated_list = list(set(my_list))
print(updated_list)
#The output will be: [1, 2, 3, 4, 5]
As we know that set
doesn't support duplicate, we can simply use this method to remove duplicates. Here I have type casted the list
into a set
and then again type casted in to list
.
- Using
dict
my_list = [1, 2, 3 , 4, 4, 5, 2]
updated_list = list(dict.fromkeys(my_list))
print(mylist)
#The output will be: [1, 2, 3, 4, 5]
Well dict
also doesn't support duplicates so when we convert the list
to dict
, so we are creating dict
from the list
and then converting it back to list.
- I don't know what to call this method
my_list = [1, 2, 3 , 4, 4, 5, 2]
updated_list = []
for item in my_list:
if item not in list:
updated_list.append(item)
my_list = updated_list
print(my_list)
#The output will be: [1, 2, 3, 4, 5]
So that was 3 ways to remove duplicates from a list.
I you got some more methods write down in the comment box below, I would love to see them, until then bey bye and
Peace ✌
Recommend
-
22
Using plain old for loop To implement this method you need another array and you can loop each element in the original array, then check whether the element co...
-
20
Leetcode Solutions (96 Part Series) This is part of a series of Leetcode solution explanations (
-
8
Remove duplicates back to back from a list on python advertisements I want to delete the back to back duplicates of a list. myL...
-
4
@ashykAshok KumarJavascript developerWe can use the Set object to remove the duplicates from an array. The Set object lets you store unique va...
-
11
Job Interview Question And Answer (7 Part Series) Interview Question #4: Write a function that will remove duplicate in an array.🤔❓ You c...
-
10
While working in javascript arrays, we often need to merge two arrays, and many times we also need to remove the duplicates from the final array. This article will see different ways to merge two arrays and remove duplicate items from the fin...
-
8
Leet Code - Remove Duplicates from Sorted Array **`Given an integer array nu...
-
7
(Remove Duplicates from Sorted List) 25 Aug 2012
-
6
Remove Duplicates From a List in C# Posted by Code Maze | Updated Date Jun 25, 2022 |
-
3
Remove Duplicates From a List in Kotlin Jan 25, 2023...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK