How to Find Unique Elements from List in Python?
A list is one of the most useful data structure in Python. It contains multiple elements, and some elements can be repeated.
Sometimes it needs to find all the unique elements from list in Python. This can be accomplished by simple python set operation.
Python syntax for set operation.
Inferring it with an example will be easy.
Code to Find Unique Elements from List in Python:
Take a list of all the computer languages. And there are some languages repeated in the list. You are asked to find all the different languages list.
listCompLang =['CPP', 'C', 'Python', 'CPP', 'Java', 'Java'] print set(listCompLang)
set(['CPP', 'Python', 'C', 'Java'])
The problem with a set is, you can not access set elements directly unlike list. So convert it into a list first and then use it as follows.
listCompLang =['CPP', 'C', 'Python', 'CPP', 'Java', 'Java'] listUniqueCL = list(set(listCompLang)) print listUniqueCL;
['CPP', 'Python', 'C', 'Java']
In the output, you can see none of the computer languages are repeated.
Note: I have tested this program on python 2.6 version. If you are running the same program on Python 3, you need to use print statement with bracket.
Related Read:3 Ways to Check if all Elements in List are Same
This simple trick is very useful in many cases.
Take an example. You want to find the frequency of all the unique elements in the list. In this case, find all unique elements from list in Python and count number of times each unique elements has appeared in the original list.
Usually, if you want to search for all the unique elements in any other language, you have to run the loop and test all the elements.
But in python, we can use a simple set operation. For this simplicity, I have listed python in top 5 Top Programming Languages to Learn.
Do you have any other way to do this? Write in a comment and let me know.
Leave a Reply