In this article, we will discuss different ways to fetch unique values from a list in Python.
Table Of Contents
Introduction
Suppose we have a list of numbers i.e.
[12, 48, 23, 48, 54, 12, 71, 48, 71, 48, 23, 48]
This list has certain repeated elements. But we want to find out all unique value in this list. Like,
[12, 48, 23, 54, 71]
There are different ways to get unique values from a list. Let’s discuss them one by one,
Get unique values in list using for loop
Create a new empty list X. Then iterate over all elements in the given list and for each element check if it exists in the new list X or not. If not then add that element to list X. When for loop ends, the list X will have all unique values from the given list.
For example,
Frequently Asked:
- Find Substring within a List in Python
- Convert a list of tuples to a list of lists in Python
- How to create a List from 1 to 100 in Python?
- Get every other element in a List in Python
listOfNums = [12, 48, 23, 48, 54, 12, 71, 48, 71, 48, 23, 48] uniqueElements = [] for elem in listOfNums: if elem not in uniqueElements: uniqueElements.append(elem) print(uniqueElements)
Output:
[12, 48, 23, 54, 71]
We fetched all unique values from a list in Python.
Get unique values in list using set
A set in python can have unique values only. So, to find the unique values from a list, we can create a set from the list. This set will have unique values only. Then we can cast this set to a new list.
For example,
listOfNums = [12, 48, 23, 48, 54, 12, 71, 48, 71, 48, 23, 48] # Get unique values from a list uniqueElements = list(set(listOfNums)) print(uniqueElements)
Output:
[71, 12, 48, 54, 23]
Get unique values in list using NumPy
Convert list to a numpy array and then pass that to numpy.unique() function. It will return an array of unique values only. Then cast it back to a list. This list will have unique values only.
For example,
import numpy as np listOfNums = [12, 48, 23, 48, 54, 12, 71, 48, 71, 48, 23, 48] # Get unique values from a list uniqueElements = list(np.unique(np.array(listOfNums))) print(uniqueElements)
Output:
[12, 23, 48, 54, 71]
Get unique values in list using Counter
Create a Counter object from the list. This counter object, will have a mapping of unique values from list and thier occurrence count. We can cast this counter object to a list. This list will have unique values only from the original list.
For example,
from collections import Counter listOfNums = [12, 48, 23, 48, 54, 12, 71, 48, 71, 48, 23, 48] # Get unique values from a list uniqueElements = list(Counter(listOfNums)) print(uniqueElements)
Output:
[12, 23, 48, 54, 71]
Summary
We learned about different ways to get unique elements from a list in Python. Happy Coding.