How to Remove List Duplicates in Python: A Step-by-Step Guide

ViaByte.Net

Method 2: Using the set() Function

The second method we’ll be looking at is using the `set()` function to remove duplicates. Here’s how to do it:

my_list = [1, 2, 2, 3, 4, 4, 5]
new_list = list(set(my_list))

print(new_list)

In the code above, we created a new set object using the `set()` function, which automatically removes duplicates. We then converted the set back into a list using the `list()` function, and printed the new list without duplicates.

This method is faster than using a loop, as it doesn’t require iterating over the entire list. However, it doesn’t preserve the original order of the list, and may not be suitable for certain scenarios.

Bagikan:

Tinggalkan komentar