Python – Find Duplicate Items of 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.
Example 1: Find Duplicate Items of List
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)
Run 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.
Related Tutorials
- Python – Traverse List except Last Element
- Python – List of Strings
- How to Insert Item at Specific Index in Python List?
- Python List of Dictionaries
- Python List of Lists
- How to Reverse Python List?
- How to Get List of all Files in Directory and Sub-directories?
- How to Get the list of all Python keywords?
- How to Access List Items in Python?
- Python Program to Find Unique Items of a List