Python Get All Unique Elements in a List
In Python, we can use several methods to get all unique elements in a list. The most common is to use set, because a set automatically removes duplicate elements. Here is a simple example:
Example
my_list
=
[
1
,
2
,
2
,
3
,
4
,
4
,
5
]
unique_elements
=
list
(
set
(
my_list
)
)
(
unique_elements
)
Code analysis:
my_listis a list containing duplicate elements.set(my_list)Convert the list to a set; the set automatically removes duplicate elements.list(set(my_list))Convert the set back to a list so that we get a list containing only unique elements.print(unique_elements)Print the result.
Output result:
[1, 2, 3, 4, 5]
This method is simple and efficient and works for most cases. If you need to preserve the order of the elements, you can use dict.fromkeys() method in the component:
Example
my_list
=
[
1
,
2
,
2
,
3
,
4
,
4
,
5
]
unique_elements
=
list
(
dict
.
fromkeys
(
my_list
)
)
(
unique_elements
)
Code analysis:
dict.fromkeys(my_list)Create a dictionary whose keys are the elements of the list; since dictionary keys are unique, duplicate elements are automatically removed.list(dict.fromkeys(my_list))Convert the dictionary keys back to a list.print(unique_elements)Print the result.
Output result:
[1, 2, 3, 4, 5]
This method preserves the original order of the elements while removing duplicates.
Python3 Examples