Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

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

1 Answer

0 votes
by (36.8k points)

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']

 Improve your knowledge in data science from scratch using Data science online courses

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...