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.
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.
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)
The unique elements of the input list using set(): 25 75 100 20 12
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)
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.
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)
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.
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.Sign up
Click below to sign up and get $100 of credit to try our products over 60 days!