Python Program - Find Duplicate Items of a List


Python - Find duplicate items in a list

To find only duplicate items of a Python List, you can check the occurrences of each item in the list, and add it to the duplicates, it the number of occurrences of this item is more than one.

An item is said to be duplicate, if it has occurred more than once in the list.

In this tutorial, we will write example programs, that help us to find the duplicate items of a list.

Examples

1: Find duplicate items in a given list of integers

In the following program, we shall take a list of numbers, and create a set out of it using set constructor.

Python Program

myList = [9, 1, 5, 9, 4, 2, 7, 2, 9, 5, 3]
occurrences = []
 
for item in myList :
    count = 0
    for x in myList :
        if x == item :
            count += 1
    occurrences.append(count)

duplicates = set()
index = 0
while index < len(myList) :
    if occurrences[index] != 1 :
        duplicates.add(myList[index])
    index += 1

print(duplicates)

Output

{9, 2, 5}

Only the duplicate elements has made it to the resulting set.

Summary

In this tutorial of Python Examples, we learned how to find unique items/elements of a list.