pythonlistduplicateslogicremove-if

Removing selected duplicates in a python list


Suppose i have the following list:

my_list = ["sam","sam", "is", "a", "is", "sam" , "good", "person", "person"]

Now my requirement is to write a function that selectively removes duplicates. I want to use this function in a for loop.

suppose i want to remove "sam" duplicates

Which means after 1st iteration my desired result is as follows:

my_list  = ["sam", "is", "a", "is", "good", "person", "person"]

only duplicates of "sam" are removed.

similarly, after the second iteration, i want to remove is "person", so my list will look like:

 my_list  = ["sam", "is", "a", "is", "good", "person"]

Please suggest a way i can do this?

Thanks & Regards


Solution

  • The cleanest way do do it I think would be to use list comprehension to remove all the appeareances of the element, and then add the element to the end. You can do something like that:

    def removeDuplicates(my_list,current):
        return [ element for element in my_list if element != current] + [current]
    

    And calling the function:

    >>> my_list
    ['sam', 'sam', 'is', 'a', 'is', 'sam', 'good', 'person', 'person']
    
    >>> my_list2 = removeDuplicates(my_list,"sam")
    >>> my_list2
    ['is', 'a', 'is', 'good', 'person', 'person', 'sam']
    
    >>> my_list3 = removeDuplicates(my_list2,"person")
    >>> my_list3
    ['is', 'a', 'is', 'good', 'sam', 'person']