Python Delete Duplicate Elements from a List
In Python, we can use several methods to delete duplicate elements from a list. Common approaches include using the set data structure, list comprehensions and the dict.fromkeys() method. Below we show how to use these methods to remove duplicates from a list.
Example
Method 1: use set
original_list
=
[
1
,
2
,
2
,
3
,
4
,
4
,
5
]
unique_list
=
list
(
set
(
original_list
)
)
(
"Method 1 result:"
,
unique_list
)
Method 2: use a list comprehension
original_list
=
[
1
,
2
,
2
,
3
,
4
,
4
,
5
]
unique_list
=
[
]
[
unique_list.
append
(
x
)
for
x
in
original_list
if
x
not
in
unique_list
]
(
"Method 2 result:"
,
unique_list
)
Method 3: use dict.fromkeys()
original_list
=
[
1
,
2
,
2
,
3
,
4
,
4
,
5
]
unique_list
=
list
(
dict
.
fromkeys
(
original_list
)
)
(
"Method 3 result:"
,
unique_list
)
Code analysis:
-
Method 1: use
set
set is a data structure in Python that does not allow duplicate elements. By converting a list to a setwe can remove duplicates automatically, then convert it back to a list.list(set(original_list)) data to the child component via original_list Converts to set, and then convert it back to a list.-
Method 2: use a list comprehension
original_listand add elements that are not in unique_list add the elements of unique_list it.[unique_list.append(x) for x in original_list if x not in unique_list] This line iterates over original_listand adds non-duplicate elements to unique_list it.-
Method 3: use
dict.fromkeys()
dict.fromkeys() The method creates a dictionary whose keys are unique, so duplicates are removed. We then convert the dictionary keys back to a list.list(dict.fromkeys(original_list)) data to the child component via original_list Convert to dictionary keys, then back to a list.Output result:
方法1结果: [1, 2, 3, 4, 5]
方法2结果: [1, 2, 3, 4, 5]
方法3结果: [1, 2, 3, 4, 5]
All methods successfully removed the duplicate elements from the list and preserved the order of the original list (except Method 1, because set does not guarantee order).
Python3 Examples