Open In App

Counting number of unique values in a Python list

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

Let us see how to count the number of unique values in a Python list. 

Examples :

Input : 10 20 10 30 40 40
Output : 2
Explanation : 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 which the frequency is 1. 

Python3




# function to count the unique elements
def count_unique(my_list):
 
    # variable to store the unique count
    count = 0
 
    # creating dictionary to count frequency
    freq = {}
 
    # traversing the list
    for x in my_list:
        if (x in freq):
            freq[x] += 1
        else:
            freq[x] = 1
 
    # traversing the dictionary
    for key, value in freq.items():
        if value == 1:
            count += 1
 
    # displaying the count of unique elements
    print(count)
 
# driver function
if __name__ == "__main__":
 
    my_list = [10, 20, 10, 30, 40, 40]
    count_unique(my_list)
 
    my_list = ['geeks', 'for', 'geeks']
    count_unique(my_list)


Output :

2
1

Time complexity : O(N) Space complexity : O(N) 

Approach 2 : Here we will be using the get() method of the dictionary class to count the frequency. This makes the program shorter and demonstrates how get() method is useful instead of if…else. 

Python3




# function to count the unique elements
def count_unique(my_list):
 
    # variable to store the unique count
    count = 0
 
    # creating dictionary to count frequency
    freq = {}
 
    # traversing the list
    for x in my_list:
        freq[x] = freq.get(x, 0) + 1
 
    # traversing the dictionary
    for key, value in freq.items():
        if value == 1:
            count += 1
 
    # displaying the count of unique elements
    print(count)
 
# driver function
if __name__ == "__main__":
 
    my_list = [10, 20, 10, 30, 40, 40]
    count_unique(my_list)
 
    my_list = ['geeks', 'for', 'geeks']
    count_unique(my_list)


Output :

2
1

Time complexity : O(N) Space complexity : O(N) 

Approach 3 : Here we will be using the count() method of the list class to count the frequency. 

Python3




# function to count the unique elements
def count_unique(my_list):
 
    # variable to store the unique count
    count = 0
 
    # creating dictionary to count frequency
    freq = {}
 
    # traversing the list
    for x in my_list:
        freq[x] = my_list.count(x)
 
    # traversing the dictionary
    for key, value in freq.items():
        if value == 1:
            count += 1
 
    # displaying the count of unique elements
    print(count)
 
# driver function
if __name__ == "__main__":
 
    my_list = [10, 20, 10, 30, 40, 40]
    count_unique(my_list)
 
    my_list = ['geeks', 'for', 'geeks']
    count_unique(my_list)


Output :

2
1

Time complexity : O(N) Space complexity : O(N)

 Approach 4 : Here we will be using the Counter() method of the collections module to count the frequency. 

Python3




# importing the module
import collections
 
# function to count the unique elements
def count_unique(my_list):
 
    # variable to store the unique count
    count = 0
 
    # creating dictionary to count frequency
    freq = collections.Counter(my_list)
 
    # traversing the dictionary
    for key, value in freq.items():
        if value == 1:
            count += 1
 
    # displaying the count of unique elements
    print(count)
 
# driver function
if __name__ == "__main__":
 
    my_list = [10, 20, 10, 30, 40, 40]
    count_unique(my_list)
 
    my_list = ['geeks', 'for', 'geeks']
    count_unique(my_list)


Output :

2
1

Time Complexity: O(n) where n is the number of elements in the list
Auxiliary Space: O(1), constant extra space required

 Approach#5: Here we will be using the reduce() method of the functools module to count the frequency. 

Python




from functools import reduce
# function to count the unique elements
def count_unique(my_list):
    # count frequency
    freq = reduce(lambda x,y : x+1 if my_list.count(y)<2 else x, my_list,0)
 
    # displaying the count of unique elements
    print(freq)
 
# driver function
if __name__ == "__main__":
 
    my_list = [10, 20, 10, 30, 40, 40]
    count_unique(my_list)
 
    my_list = ['geeks', 'for', 'geeks']
    count_unique(my_list)


Output

2
1

Time complexity : O(n), where n is length of my_list

Auxiliary space : O(n), where n is length of my_list

Approach#6: Using Counter() function

Python3




from collections import Counter
# function to count the unique elements
 
 
def count_unique(my_list):
    freq = Counter(my_list)
    res = 0
    for key, value in freq.items():
        if(value == 1):
            res += 1
    print(res)
 
 
# driver function
if __name__ == "__main__":
 
    my_list = [10, 20, 10, 30, 40, 40]
    count_unique(my_list)
 
    my_list = ['geeks', 'for', 'geeks']
    count_unique(my_list)


Output

2
1

Time Complexity: O(N)

Auxiliary Space: O(N)

Approach 7:  using operator.countOf() method

Python3




import operator as op
# function to count the unique elements
 
 
def count_unique(my_list):
 
    # variable to store the unique count
    count = 0
 
    # creating dictionary to count frequency
    freq = {}
 
    # traversing the list
    for x in my_list:
        freq[x] = op.countOf(my_list, x)
 
    # traversing the dictionary
    for key, value in freq.items():
        if value == 1:
            count += 1
 
    # displaying the count of unique elements
    print(count)
 
 
# driver function
my_list = [10, 20, 10, 30, 40, 40]
count_unique(my_list)
 
my_list = ['geeks', 'for', 'geeks']
count_unique(my_list)


Output

2
1

Time Complexity: O(N)

Auxiliary Space : O(N)

Approach #8: Using defaultdict()

Here is the algorithm for the count_unique function:

  1. Create an empty defaultdict object unique_dict with default value int.
  2. Iterate through the elements x of the input list my_list.
  3. For each x, increment the value corresponding to x in unique_dict.
  4. Iterate through the values of unique_dict and count the number of values equal to 1.
  5. Print the count as output.

Python3




from collections import defaultdict
 
def count_unique(my_list):
    unique_dict = defaultdict(int)
    for x in my_list:
        unique_dict[x] += 1
    res = sum(1 for x in unique_dict.values() if x == 1)
    print(res)
 
 
if __name__ == "__main__":
    my_list = [10, 20, 10, 30, 40, 40]
    count_unique(my_list)
 
    my_list = ['geeks', 'for', 'geeks']
    count_unique(my_list)
#This code is contributed by Vinay Pinjala.


Output

2
1

Time complexity: O(n) where n is the length of the input list my_list. This is because the function iterates through each element of my_list exactly once.

Auxiliary Space: O(k) where k is the number of unique elements in my_list. This is because the defaultdict unique_dict will have at most k key-value pairs, where k is the number of unique elements in my_list



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 | 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
How to count unique values inside a list
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
3 min read
Counting the frequencies in a list using dictionary in Python
Given an unsorted list of some elements(which may or may not be integers), Find the frequency of each distinct element in the list using a Python dictionary. Example: Input: [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] Output: 1 : 5 2 : 4 3 : 3 4 : 3 5 : 2 Explanation: Here 1 occurs 5 times, 2 occurs 4 times and so on... The problem can be s
4 min read
Python | Counting sign change in list containing Positive and Negative Integers
Given a list containing Positive and Negative integers, We have to find number of times the sign(Positive or Negative) changes in the list. Input: [-1, 2, 3, -4, 5, -6, 7, 8, -9, 10, -11, 12] Output:9 Explanation : Sign change from -1 to 2, ans = 1 Sign change from 3 to -4, ans = 2 Sign change from -4 to 5, ans = 3 Sign change from 5 to -6, ans = 4
5 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
Python | Unique values in Matrix
Sometimes we need to find the unique values in a list, which is comparatively easy and has been discussed earlier. But we can also get a matrix as input i.e a list of lists, and finding unique in them are discussed in this article. Let's see certain ways in which this can be achieved. Method #1: Using set() + list comprehension The set function can
9 min read
Python | Test if dictionary contains unique keys and values
Sometimes, we just wish to work with unique elements and any type of repetition is not desired, for these cases, we need to have techniques to solve these problems. One such problem can be to test for unique keys and values. For keys, they are by default unique, hence no external testing is required, but as for values, we need to have ways to do it
6 min read
Python - Unique values Multiplication
This article focuses on one of the operation of getting the unique list from a list that contains a possible duplicates and performing its product. This operations has large no. of applications and hence it’s knowledge is good to have. Method 1 : Naive method + loop In naive method, we simply traverse the list and append the first occurrence of the
5 min read