Python Find Duplicate Elements in List

Document 对象参考手册Python3 Examples

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))

Code explanation:

  1. seenis a set used to store elements that have already appeared.
  2. duplicatesis a set used to store duplicate elements.
  3. Traverse the listlst, for each elementitem:
    • ifitemalready inseenthe set, then add it toduplicatesthe set.
    • Otherwise, additemtoseenthe set.
  4. Finally, convertduplicatesset to a list and return.

Output result:

Example

[2, 3, 5]

Document 对象参考手册Python3 Examples

Other Extensions