How to find Duplicate Elements from a List in Python
A list in Python can have any number of duplicate elements. To find duplicate elements from a list, you can simply loop through the list and check for matching items as shown in the example code below:
def find_duplicates(list):
list.sort()
duplicates = []
for item in range(0,len(list)-1):
if list[item] == list[item+1]:
duplicates.append(list[item])
return duplicates
fruits = ["banana", "apple", "grapes", "mango", "apple", "watermelon", "banana"]
result = find_duplicates(fruits)
print("Duplicate elements in the list = ",result)
The output of the above code is as follows:
Duplicate elements in the list = ['apple', 'banana']