In this article, we will be understanding 3 ways to get unique values from a Python list. While dealing with a huge amount of raw data, we often come across situations wherein we need to fetch out the unique and non-repeated set of data from the raw input data-set.
The methods listed below will help you solve this problem. Let’s get right into it!
Either of the following ways can be used to get unique values from a list in Python:
As seen in our previous tutorial on Python Set, we know that Set stores a single copy of the duplicate values into it. This property of set can be used to get unique values from a list in Python.
Syntax:
Syntax:
Example:
Output:
In order to find the unique elements, we can apply a Python for loop along with list.append() function to achieve the same.
Syntax:
Example:
Output:
Python NumPy module has a built-in function named, numpy.unique to fetch unique data items from a numpy array.
Syntax:
Syntax:
Example:
Output:
In this article, we have unveiled various ways to fetch the unique values from a set of data items in a Python list.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.