How to create a list of unique elements in Python?

To create a list of unique elements in Python, you can use the following methods:

  1. Using the set() function:
original_list = [1, 2, 2, 3, 4, 4, 5] unique_list = list(set(original_list)) print(unique_list)
  1. Using loop:
original_list = [1, 2, 2, 3, 4, 4, 5] unique_list = [] for element in original_list: if element not in unique_list: unique_list.append(element) print(unique_list)
  1. Using list comprehension:
original_list = [1, 2, 2, 3, 4, 4, 5] unique_list = [element for element in original_list if element not in unique_list] print(unique_list)

All three methods will produce the following output:

[1, 2, 3, 4, 5]

Note: The set() function is the most efficient and fastest approach to find unique elements because it automatically removes duplicates by its nature. However, using the loop or list comprehension methods allows you to preserve the original order of the elements.