How to remove duplicates from a list in Python?

There are several ways to remove duplicates from a list in Python. Here are a few methods:

  1. Using a set: Convert the list to a set, which automatically removes duplicate elements, and then convert it back to a list.
my_list = [1, 2, 3, 3, 4, 5, 5, 6] my_list = list(set(my_list)) print(my_list) # Output: [1, 2, 3, 4, 5, 6]
  1. Using a loop: Create a new list and iterate over the original list, adding each element to the new list only if it hasn't been added before.
my_list = [1, 2, 3, 3, 4, 5, 5, 6] new_list = [] for item in my_list: if item not in new_list: new_list.append(item) print(new_list) # Output: [1, 2, 3, 4, 5, 6]
  1. Using list comprehension: Use a list comprehension to filter out the duplicates by checking if an item is already in the new list.
my_list = [1, 2, 3, 3, 4, 5, 5, 6] new_list = [item for item in my_list if item not in new_list] print(new_list) # Output: [1, 2, 3, 4, 5, 6]

These are some commonly used methods for removing duplicates from a list in Python. Choose the method that best suits your needs and the complexity requirements of your program.