Python Get All Unique Elements in a List

Document 对象参考手册Python3 Examples

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)

Code explanation:

  1. my_listis a list containing duplicate elements.
  2. set(my_list)Convert the list to a set, and the set will automatically remove duplicate elements.
  3. list(set(my_list))Convert the set back to a list so that we can get a list containing only unique elements.
  4. 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)

Code explanation:

  1. 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.
  2. list(dict.fromkeys(my_list))Convert the dictionary keys back to a list.
  3. 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.

Document 对象参考手册Python3 Examples

Other extensions