Python Get Duplicate Elements in List
We can use Python's set and list to get duplicate elements in a list. A set is an unordered collection of unique elements, so we can use the characteristics of sets to find duplicate elements in a list.
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, 7]
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, 7]
print(find_duplicates(my_list))
Code explanation:
find_duplicatesThe function accepts a listlstas a parameter.seenis a set used to store elements that have already been traversed.duplicatesis a set used to store duplicate elements.- Traverse the list
lsteach element in:- If the element is already in
seenset, add it toduplicatesset. - Otherwise, add the element to
seenset.
- If the element is already in
- Finally, convert
duplicatesset to a list and return it.
Output result:
Example
[2, 3, 7]
This output indicates that in the example listmy_list, the elements2、3and7are duplicates.
Python3 Examples