Contents
Python – Find Unique Items of 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.
Example 1: Find Unique Items of List using Set
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)
Run Output
{1, 2, 3, 4, 5, 7, 9}
Only the unique elements has made it to the resulting set.
Example 2: Find Unique Elements of a 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)
Run 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.
Related Tutorials
- How to Insert Item at Specific Index in Python List?
- Python – Count the items with a specific value in the List
- Python Program to Find Duplicate Items of a List
- How to Reverse Python List?
- Python – List of Strings
- How to Sort Python List?
- Python Program to Find Smallest Number in List
- How to Append List to Another List in Python? – list.extend(list)
- Python – How to Create an Empty List?
- How to Check if Python List is Empty?