Find Duplicates in a List -Python

The task is to identify all duplicate elements in a given list. For instance, if we have a list like [1, 2, 3, 1, 2, 4], the expected output should be a list of duplicates, which in this case would be [1, 2]

def find_duplicates(lst):
    seen = set()
    duplicates = set()
    
    for x in lst:
        if x in seen:
            duplicates.add(x)
        else:
            seen.add(x)
    
    return list(duplicates)

# Example usage
duplicates = find_duplicates([1, 2, 3, 1, 2, 4])
print(duplicates)  # Output: [1, 2]

The provided code defines a function find_duplicates that takes a list as input and returns a list of duplicate elements.

  1. A seen set is used to track elements that have already been encountered.
  2. If an element is found in seen, it is added to the duplicates set, indicating it’s a duplicate. Otherwise, the element is added to seen.
  3. Finally, the duplicates are returned as a list.