Let’s create a list that will only have unique elements. In other words, we will add value only if there is no same value inside our list.
1 2 3 4 5 6 7 8 9 10 11 12 |
unique_list = [] list_with_elements = [5, 2, 4, 3, 4, 1, 6, 10, 2, 7, 8, 9, 10, 6, 5, 3, 7, 6, 5, 3] def add_unique(list, value): if value in list: return False list.append(value) for element in list_with_elements: add_unique(unique_list, element) print(unique_list) |
Inside the code, there is the for loop. This loop iterates through each element of the list_of_elements list and checks whether the value is already inside the unique_list list. If it’s not present, the program adds this element. Otherwise, it returns False and checks the next iteration.
If you run this code, you are going to get the following result:
[5, 2, 4, 3, 1, 6, 10, 7, 8, 9]
As you can see, there are no duplicates – each value is unique.