Sometimes, you may need to check whether a list has any duplicate elements. This can be a common task when you are given a list of numbers or a list of strings. This can also be something that you may need to do both at work, or it can also be part of a coding challenge that you are implementing when being asked at a programming interview.
This implementation can be done in a few ways, but here, we are going to describe a really quick way.
The following method checks whether the given list has duplicate elements. It uses the property of set() which removes duplicate elements from the list.
Let us assume that we have a list like the following:
my_list = [1, 2, 3, 4, 5, 3, 4, 2, 1]
We can use the set() method to remove the duplicate elements from the list and then check whether the set and the list have the same length. If they have the same length, it means that when we did the conversion from a list to a set, we did not remove any element. If they have different lengths, it means that we removed some elements.
Let us see this in action:
len(my_list) == len(set(my_list)) # False
In our specific example, we have some duplicate elements, hence the length of the list is not equal to the length of the set.
That’s basically it for this article.
I hope you find it useful.