Python Program - Find Unique Items of a List
Python - Find unique items in a list
To find unique items of a list, you can take help of a Python Set, or use for loop and iterate over, to check if the item is unique or not.
An item is said to be unique, if it has occurred only once in the list.
In this tutorial, we will write example programs, that help us to find the unique items of a list.
Examples
1. Find unique items in given list using set() built-in function
Python List is an ordered collection of elements. Duplicates are allowed.
Python Set is a collection of unique elements. We can use this property of a Python Set to get only the unique items of a list.
To get only unique items of a list, use Python set constructor. Pass the list as argument to the set constructor, and it returns a set of unique elements.
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]
mySet = set(myList)
print(mySet)
Output
{1, 2, 3, 4, 5, 7, 9}
Only the unique elements has made it to the resulting set.
2. Find unique elements in a given list using For loop
We can also use a looping statement like, Python While Loop or Python For Loop, to iterate over the elements of the list, and check if the element has occurred only once.
In the following program, we will use nested for loop. The outer for loop is to check if each element is unique or not. The inner for loop is to compare this element with collected unique elements.
Algorithm
- Read or take a list myList.
- Initialize an empty list uniqueList.
- For each item in myList
- Assume that item is not in myList. Initialize itemExist to False.
- For each element x in uniqueList
- Check if item is equal to x. If so, you already have this item in your uniqueList. Set itemExist to True and break the loop.
- If itemExist is False, add item to uniqueList.
- uniqueList contains unique elements of myList.
Python Program
myList = [9, 1, 5, 9, 4, 2, 7, 2, 9, 5, 3]
uniqueList = []
for item in myList :
itemExist = False
for x in uniqueList :
if x == item :
itemExist = True
break
if not itemExist :
uniqueList.append(item)
print(uniqueList)
Output
[9, 1, 5, 4, 2, 7, 3]
The advantage of this process is that, the order of unique elements is unchanged.
Summary
In this tutorial of Python Examples, we learned how to find unique items/elements of a list.