Python Get All Unique Elements in a List
In Python, we can use multiple methods to get all unique elements in a list. The most common method is to useset, 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))
print(unique_elements)
unique_elements = list(set(my_list))
print(unique_elements)
Code explanation:
my_listis a list containing duplicate elements.set(my_list)Convert the list to a set, and the set will automatically remove duplicate elements.list(set(my_list))Convert the set back to a list so that we can 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 is suitable for most cases. If you need to preserve the order of elements, you can use thedict.fromkeys()method:
Example
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_elements = list(dict.fromkeys(my_list))
print(unique_elements)
unique_elements = list(dict.fromkeys(my_list))
print(unique_elements)
Code explanation:
dict.fromkeys(my_list)Create a dictionary. The keys of the dictionary are the elements in 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 removes duplicate elements while maintaining the original order of elements.
Other extensions
Python3 Examples