MacBook Pro, white ceramic mug,and black smartphone on table
Photo by Andrew Neel on Unsplash

Lists are part of typically every project that you work on these days. You have lists of people, a list of products, a list of activities, and the list of lists goes on.

There can be times when you want to only have unique elements in that list, for example, if someone has liked multiple posts and you want to get all the people who have liked one of your posts. You do not want to include that same person multiple times in that list.

I know that this is not a really good example, but it should at least help drive the point home for you in case you were wondering that such questions only appear in job interviews and not in real-world projects.

Now, enough with talking and let’s jump into coding it.

Well, there can be a few ways you can use to remove duplicate elements in a list, but I am going to show you two ways.

One way can be by saving unique elements in a new list by iterating through the original list and not including elements that have been already inserted in the new list:

Another one that you can use is taking advantage of the fact that sets do not allow duplicate elements to be part of it.

In this case, we don’t need to check whether the element has already been added to the set or not, since sets do not allow the same element to be added twice it.

We are converting the result back to a list so that we can have a more user-friendly print.

That’s pretty much. I hope you find it useful.