Python Find Duplicate Elements in List
In Python, finding duplicate elements in a list can be implemented in multiple ways. A common method is to use a set to store elements that have already appeared, then traverse the list and check whether each element already exists in the set. If it exists, that element is a duplicate.
Example
def find_duplicates(lst):
seen = set()
duplicates = set()
for item in lst:
if item in seen:
duplicates.add(item)
else:
seen.add(item)
return list(duplicates)
# Example list
my_list = [1, 2, 3, 2, 4, 5, 3, 6, 7, 8, 5]
print(find_duplicates(my_list))
seen = set()
duplicates = set()
for item in lst:
if item in seen:
duplicates.add(item)
else:
seen.add(item)
return list(duplicates)
# Example list
my_list = [1, 2, 3, 2, 4, 5, 3, 6, 7, 8, 5]
print(find_duplicates(my_list))
Code explanation:
seenis a set used to store elements that have already appeared.duplicatesis a set used to store duplicate elements.- Traverse the list
lst, for each elementitem:- if
itemalready inseenthe set, then add it toduplicatesthe set. - Otherwise, add
itemtoseenthe set.
- if
- Finally, convert
duplicatesset to a list and return.
Output result:
Example
[2, 3, 5]
Python3 Examples