search

How to remove duplicates from alist in Python?

To remove duplicates from a list in Python, you can convert the list to a set and then convert it back to a list. Here's an example:

my_list = [1, 2, 3, 2, 4, 1, 5, 3, 4]
unique_list = list(set(my_list))
print(unique_list)
# Output: [1, 2, 3, 4, 5]

In this example, the set() function is used to convert the list my_list to a set. A set is an unordered collection of unique elements, so any duplicates are automatically removed. Then, the list() function is used to convert the resulting set back to a list. The resulting list unique_list contains only the unique elements from the original list.

Note that the order of the elements may not be preserved because sets are unordered. If you need to maintain the original order, you can use a different approach, such as using a loop to iterate over the original list and add only the non-duplicate elements to a new list.

Alternatively, you can use list comprehension with a condition to filter out duplicates while preserving the order:

my_list = [1, 2, 3, 2, 4, 1, 5, 3, 4]
unique_list = [x for i, x in enumerate(my_list) if x not in my_list[:i]]
print(unique_list)
# Output: [1, 2, 3, 4, 5]

In this approach, a list comprehension is used to iterate over the elements of my_list. The condition x not in my_list[:i] ensures that only the first occurrence of each element is added to the unique_list. This way, duplicates are filtered out, and the order of the elements is preserved.

Related Questions You Might Be Interested