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

ViaByte.Net

Hello Viabyte, welcome to this article where we’ll be discussing how to remove duplicates from a list in Python. If you’re a developer or programmer, you’ve probably come across a scenario where you need to remove duplicates from a list, and you’re not sure how to do it. Fortunately, Python provides several ways to remove duplicates from a list, and in this article, we’ll be exploring some of them.

Method 1: Using a Loop

The first method we’ll be looking at is using a loop to iterate over the list and remove duplicates. Here’s how to do it:

my_list = [1, 2, 2, 3, 4, 4, 5]
new_list = []

for item in my_list:
    if item not in new_list:
        new_list.append(item)

print(new_list)

In the code above, we created a new empty list called `new_list`. We then looped through the original list (`my_list`) and checked if each item was already in `new_list`. If it wasn’t, we added it to the list. Finally, we printed the new list without duplicates.

This method works well for small lists, but can be slow for larger lists, as it requires iterating over the entire list for every item.

Bagikan:

Tinggalkan komentar