In Python, you can use sets to easily find the unique elements of a list or other iterable. Here's an example:
my_list = [1, 2, 2, 3, 3, 3, 4, 5, 5]unique_set = set(my_list)print(unique_set) |
Output:
{1, 2, 3, 4, 5} |
In the above code, my_list contains several duplicates. We create a new set, unique_set, by passing my_list to the set() constructor. The resulting set contains only the unique elements of my_list.
Note that the order of the elements in the set is not preserved, because sets are unordered collections in Python. If you need to maintain the order of the original list, you can use a list and a for loop to add each element to the new list only if it hasn't been added before:
my_list = [1, 2, 2, 3, 3, 3, 4, 5, 5]unique_list = []for element in my_list: if element not in unique_list: unique_list.append(element)print(unique_list) |
Output:
[1, 2, 3, 4, 5] |
In this version of the code, we use a list, unique_list, instead of a set. We iterate over each element in my_list, and add it to unique_list only if it hasn't been added before. The resulting unique_list contains the same elements as the unique_set in the previous example, but in the order they appeared in the original list.