Open In App

How to count unique values inside a list

Last Updated : 19 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

There are several methods for finding or counting unique items inside a list in Python. Here we’ll discuss 3 methods.

Method 1: 

The first method is the brute force approach. This method is not very much efficient as it takes more time and space. In this method, we take an empty array and a count variable(set to be zero). We traverse from the start and check the items. If the item is not in the empty list(as it has taken empty) then we will add it to the empty list and increase the counter by 1. While traveling if the item is in the taken list(empty list) we will not count it. 

Example: 

Python3




# taking an input list
input_list = [1, 2, 2, 5, 8, 4, 4, 8]
 
# taking an input list
l1 = []
 
# taking an counter
count = 0
 
# traversing the array
for item in input_list:
    if item not in l1:
        count += 1
        l1.append(item)
 
# printing the output
print("No of unique items are:", count)


Output:

No of unique items are: 5

Time complexity: O(n), where n is the length of the list
Auxiliary Space: O(n), extra space of size n is required

Method 2:

In this method, we will use a function name Counter. The module collections have this function. Using the Counter function we will create a dictionary. The keys of the dictionary will be the unique items and the values will be the number of that key present in the list.  We will create a list using the keys, the length of the list will be our answer.

Python3




# importing Counter module
from collections import Counter
 
 
input_list = [1, 2, 2, 5, 8, 4, 4, 8]
 
# creating a list with the keys
items = Counter(input_list).keys()
print("No of unique items in the list are:", len(items))


Output:

No of unique items in the list are: 5

If we print the length of the dictionary created using Counter will also give us the result. But this method is more understandable.

Method 3:

In this method, we will convert our list to set. As sets don’t contain any duplicate items then printing the length of the set will give us the total number of unique items.

Python3




input_list = [1, 2, 2, 5, 8, 4, 4, 8]
 
# converting our list to set
new_set = set(input_list)
print("No of unique items in the list are:", len(new_set))


Output:

No of unique items in the list are: 5

Time complexity: O(n), where n is the length of input_list
Auxiliary Space: O(n), extra space required for set.

Method 4:

In this method, we will remove all the duplicate from our list. As list  don’t contain any duplicate items then printing the length of the list will give us the total number of unique items.

Python




input_list = [1, 2, 2, 5, 8, 4, 4, 8]
 
# converting our list to filter list
new_set = [ x for i, x in enumerate(input_list) if x not in input_list[:i]]
print("No of unique items in the list are:", len(new_set))


Output:

No of unique items in the list are: 5


Next Article

Similar Reads

Python - Extract Unique values dictionary values
Sometimes, while working with data, we can have problem in which we need to perform the extraction of only unique values from dictionary values list. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Extract Unique values dictionary values Using sorted() + set comprehen
7 min read
Python - Unique values count of each Key
Given a Dictionaries list, the task is to write a Python program to count the unique values of each key. Example: Input : test_list = [{"gfg" : 1, "is" : 3, "best": 2}, {"gfg" : 1, "is" : 3, "best" : 6}, {"gfg" : 7, "is" : 3, "best" : 10}] Output : {'gfg': 2, 'is': 1, 'best': 3} Explanation : gfg has 1 and 7 as unique elements, hence 2.Input : test
7 min read
Count unique values with Pandas per groups
Prerequisites: Pandas In this article, we are finding and counting the unique values present in the group/column with Pandas. Unique values are the distinct values that occur only once in the dataset or the first occurrences of duplicate values counted as unique values. Approach:Import the pandas library.Import or create dataframe using DataFrame()
7 min read
How to count unique values in a Pandas Groupby object?
Here, we can count the unique values in Pandas groupby object using different methods. This article depicts how the count of unique values of some attribute in a data frame can be retrieved using Pandas. Method 1: Count unique values using nunique() The Pandas dataframe.nunique() function returns a series with the specified axis's total number of u
3 min read
How to count the frequency of unique values in NumPy array?
Let's see How to count the frequency of unique values in the NumPy array. Python’s Numpy library provides a numpy.unique() function to find the unique elements and their corresponding frequency in a NumPy array. numpy.unique() Syntax Syntax: numpy.unique(arr, return_counts=False) Return: Sorted unique elements of an array with their corresponding f
4 min read
Python | Get unique values from a list
In this article, we will explore various techniques and strategies for efficiently extracting distinct elements from a given list. By delving into methods ranging from traditional loops to modern Pythonic approaches with Python. Input : [1,2, 1, 1, 3, 4, 3, 3, 5 ]Output : [1, 2, 3, 4, 5] Explaination: The output only contains the unique element fro
7 min read
Python | Get Unique values from list of dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to find the unique values over all the dictionaries in a list. This kind of utility can occur in case while working with similar data and we wish to extract the unique ones. Let's discuss certain ways in which this task can be performed. Method #1 : Using set(
4 min read
Counting number of unique values in a Python list
Let us see how to count the number of unique values in a Python list. Examples : Input : 10 20 10 30 40 40Output : 2Explanation : Only 2 elements, 20 and 30 are unique in the list. Input : 'geeks' 'for' 'geeks'Output : 1 Approach 1: Traversing the list and counting the frequency of each element using a dictionary, finally counting the elements for
6 min read
Calculate Spider Chart Values Based on Bounding Boxes Inside Chart Segments
The Spider charts also known as radar or spider web charts are useful for visualizing multivariate data in the form of a two-dimensional chart with the multiple axes originating from the same point. Calculating values for the spider chart segments can be challenging especially when dealing with irregular shapes such as the bounding boxes. In this a
3 min read
Python - Assign values to Values List
Given 2 dictionaries, assign values to value list elements mapping from dictionary 2. Input : test_dict = {'Gfg' : [3, 6], 'best' :[9]}, look_dict = {3 : [1, 5], 6 : "Best", 9 : 12} Output : {'Gfg': {3: [1, 5], 6: 'Best'}, 'best': {9: 12}} Explanation : 3 is replaced by key 3 and value [1, 5] and so on. Input : test_dict = {'Gfg' : [3, 6]}, look_di
6 min read
Practice Tags :
three90RightbarBannerImg