Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Get All Unique Elements in a List

Python Get All Unique Elements in a List

Document Object Reference Manual Python3 Examples

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

)

)

print

(

unique_elements

)

Code analysis:

  1. my_list is a list containing duplicate elements.
  2. set(my_list) Convert the list to a set; the set automatically removes duplicate elements.
  3. list(set(my_list)) Convert the set back to a list so that we 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 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

)

)

print

(

unique_elements

)

Code analysis:

  1. 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.
  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 preserves the original order of the elements while removing duplicates.

Document Object Reference Manual Python3 Examples