Tuesday 21 September 2021

Python: Remove duplicate elements from a list

Approach 1: Create a temp list, traverse the list element by element, and add it to the temp list, if the element is not part of temp list.

 

remove_duplicates_1.py

def remove_duplicates(my_list):
    new_list = []

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

    return new_list


my_list = [2, 3, 4, 5, 3, 4]
new_list = remove_duplicates(my_list)

print("my_list -> ", my_list)
print("new_list -> ", new_list)

 

Output

my_list ->  [2, 3, 4, 5, 3, 4]
new_list ->  [2, 3, 4, 5]

 

Approach 2: Add the elements of list to a set and convert the set to list and return.

 

Example

list(set(my_list))

 

Find the below working application.

 

remove_duplicates_2.py

def remove_duplicates(my_list):
    return list(set(my_list))

my_list = [2, 3, 4, 5, 3, 4]
new_list = remove_duplicates(my_list)

print("my_list -> ", my_list)
print("new_list -> ", new_list)

 

Output

my_list ->  [2, 3, 4, 5, 3, 4]
new_list ->  [2, 3, 4, 5]



Previous                                                    Next                                                    Home

No comments:

Post a Comment