Find Duplicates in a List in Python

  • Post category:List

Finding duplicates in a list is a common task in Python programming. In this blog post, we’ll explore different code examples that demonstrate how to identify duplicates efficiently.

Example 1:

numbers = [1, 2, 3, 2, 4, 5, 3]
duplicates = set(x for x in numbers if numbers.count(x) > 1)
print(duplicates)

Output: {2, 3}

Example 2:

fruits = ['apple', 'banana', 'orange', 'kiwi', 'banana', 'kiwi']
duplicates = set(x for x in fruits if fruits.count(x) > 1)
print(duplicates)

Output: {‘banana’, ‘kiwi’}