Python Get Duplicate Elements in List

Document 对象参考手册Python3 Examples

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

Code explanation:

  1. find_duplicatesThe function accepts a listlstas a parameter.
  2. seenis a set used to store elements that have already been traversed.
  3. duplicatesis a set used to store duplicate elements.
  4. Traverse the listlsteach element in:
    • If the element is already inseenset, add it toduplicatesset.
    • Otherwise, add the element toseenset.
  5. Finally, convertduplicatesset 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.

Document 对象参考手册Python3 Examples

Other Extensions