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:
set(input_list_name)
Syntax:
list(set-name)
Example:
list_inp = [100, 75, 100, 20, 75, 12, 75, 25]
set_res = set(list_inp)
print("The unique elements of the input list using set():\n")
list_res = (list(set_res))
for item in list_res:
print(item)
Output:
The unique elements of the input list using set():
25
75
100
20
12
In order to find the unique elements, we can apply a Python for loop along with list.append() function to achieve the same.
Syntax:
list.append(value)
Example:
list_inp = [100, 75, 100, 20, 75, 12, 75, 25]
res_list = []
for item in list_inp:
if item not in res_list:
res_list.append(item)
print("Unique elements of the list using append():\n")
for item in res_list:
print(item)
Output:
Unique elements of the list using append():
100
75
20
12
25
Python NumPy module has a built-in function named, numpy.unique to fetch unique data items from a numpy array.
Syntax:
numpy.array(list-name)
Syntax:
numpy.unique(numpy-array-name)
Example:
import numpy as N
list_inp = [100, 75, 100, 20, 75, 12, 75, 25]
res = N.array(list_inp)
unique_res = N.unique(res)
print("Unique elements of the list using numpy.unique():\n")
print(unique_res)
Output:
Unique elements of the list using numpy.unique():
[12 20 25 75 100]
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.