OneBite.Dev - Coding blog in a bite size

remove duplicates from an array in python

Code snippet on how to remove duplicates from an array in python

mylist = [1, 2, 3, 2, 3, 4, 1]
final_list = []
for num in mylist:
    if num not in final_list:
        final_list.append(num)

print(final_list) # Output: [1, 2, 3, 4]

This code snippet uses a for loop to traverse through the elements of the given list. As the loop iterates over each element, it checks if it already exists in the final list. If the element is not already present in the final list, the element is added to the end of the list. After the loop finishes, the final list only contains unique elements from the original list. In this example, the original list contains the elements [1, 2, 3, 2, 3, 4, 1], and the output list contains [1, 2, 3, 4], which are only the unique elements from the original list.

python