Programming Tutorials

Remove duplicates from a list in python

By: Koothrapalli in Python Tutorials on 2012-04-07  

To remove duplicates from a list in Python, there are several approaches you can take. Here are three common methods:

  1. Using a loop and a new list:

    my_list = [1, 2, 2, 3, 3, 3, 4, 5, 5]
    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]
    

    In this approach, we iterate over the original list and check if each item is already in a new list. If it's not, we add it to the new list. This way, only the unique items are included in the new list.

  2. Using a set:
    my_list = [1, 2, 2, 3, 3, 3, 4, 5, 5]
    new_list = list(set(my_list))
    
    print(new_list)  # Output: [1, 2, 3, 4, 5]
    

    In this approach, we convert the original list to a set, which automatically removes duplicates. We then convert the set back to a list to preserve the order of the original list.

  3. Using a list comprehension:
    my_list = [1, 2, 2, 3, 3, 3, 4, 5, 5]
    new_list = [item for index, item in enumerate(my_list) if item not in my_list[:index]]
    
    print(new_list)  # Output: [1, 2, 3, 4, 5]
    

    In this approach, we use a list comprehension to iterate over the original list and only include items that haven't been seen before (i.e., items that don't appear earlier in the list). We use the enumerate() function to get the index of each item in the list, and we use list slicing to get a sublist of all the items that come before the current item.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Python )

Latest Articles (in Python)