Open In App
Related Articles

Python | Frequency grouping of list elements

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Sometimes, while working with lists, we can have a problem in which we need to group element along with it’s frequency in form of list of tuple. Let’s discuss certain ways in which this task can be performed. 

Method #1: Using loop This is a brute force method to perform this particular task. In this, we iterate each element, check in other lists for its presence, if yes, then increase it’s count and put to tuple. 

Python3

# Python3 code to demonstrate working of
# Frequency grouping of list elements
# using loop
 
# initialize list
test_list = [1, 3, 3, 1, 4, 4]
 
# printing original list
print("The original list : " + str(test_list))
 
# Frequency grouping of list elements
# using loop
res = []
temp = dict()
for ele in test_list:
    if ele in temp:
        temp[ele] = temp[ele] + 1
    else:
        temp[ele] = 1
for key in temp:
    res.append((key, temp[key]))
 
# printing result
print("Frequency of list elements : " + str(res))

                    

Output
The original list : [1, 3, 3, 1, 4, 4]
Frequency of list elements : [(1, 2), (3, 2), (4, 2)]

Time complexity: O(n)
Auxiliary space: O(n)

Method #2: Using Counter() + items() The combination of two functions can be used to perform this task. They perform this task using inbuild constructs and are a shorthand to perform this task. 

Python3

# Python3 code to demonstrate working of
# Frequency grouping of list elements
# using Counter() + items()
from collections import Counter
 
# initialize list
test_list = [1, 3, 3, 1, 4, 4]
 
# printing original list
print("The original list : " + str(test_list))
 
# Frequency grouping of list elements
# using Counter() + items()
res = list(Counter(test_list).items())
 
# printing result
print("Frequency of list elements : " + str(res))

                    

Output
The original list : [1, 3, 3, 1, 4, 4]
Frequency of list elements : [(1, 2), (3, 2), (4, 2)]

Time complexity: O(n) where n is the number of elements in the input list “test_list”.
Auxiliary space: O(n) as well, where n is the number of elements in the input list “test_list”. 

Method #3 : Using set(),list(),count() methods

Python3

# Python3 code to demonstrate working of
# Frequency grouping of list elements
# using loop
 
# initialize list
test_list = [1, 3, 3, 1, 4, 4]
 
# printing original list
print("The original list : " + str(test_list))
 
# Frequency grouping of list elements
# using loop
res = []
x = list(set(test_list))
for i in x:
    res.append((i, test_list.count(i)))
# printing result
print("Frequency of list elements : " + str(res))

                    

Output
The original list : [1, 3, 3, 1, 4, 4]
Frequency of list elements : [(1, 2), (3, 2), (4, 2)]

Time complexity: O(n^2) where n is the length of the list.
Auxiliary space: O(n) where n is the length of the list. 

Method #4 : Using operator.countOf() method

Python3

# Python3 code to demonstrate working of
# Frequency grouping of list elements
# using loop
import operator as op
# initialize list
test_list = [1, 3, 3, 1, 4, 4]
 
# printing original list
print("The original list : " + str(test_list))
 
# Frequency grouping of list elements
# using loop
res = []
x = list(set(test_list))
for i in x:
    res.append((i, op.countOf(test_list,i)))
# printing result
print("Frequency of list elements : " + str(res))

                    

Output
The original list : [1, 3, 3, 1, 4, 4]
Frequency of list elements : [(1, 2), (3, 2), (4, 2)]

Time Complexity: O(N)
Auxiliary Space: O(N)

Method #5: Using dictionary

One approach to find the frequency grouping of list elements is to use a dictionary to store the count of each element in the list. You can iterate through the list and update the count of each element in the dictionary. Finally, you can iterate through the dictionary to create a list of tuples that represent the element and its count

Python3

test_list = [1, 3, 3, 1, 4, 4]
freq_dict = {}
for element in test_list:
    if element in freq_dict:
        freq_dict[element] += 1
    else:
        freq_dict[element] = 1
res = list(freq_dict.items())
print("Frequency of list elements : " + str(res))

                    

Output
Frequency of list elements : [(1, 2), (3, 2), (4, 2)]

Time Complexity: O(n), where n is the length of the input list. 
Auxiliary Space: The space complexity of this code is O(k), where k is the number of unique elements in the input list. 

Method #6: Using numpy

This approach uses the numpy library to find the unique elements and their respective counts in the input list. The np.unique() function returns two arrays: one containing the unique elements in the input array, and the other containing the number of occurrences of each unique element. We then use the zip() function to combine the two arrays into a list of tuples, which gives us the desired output.

Python3

import numpy as np
test_list = [1, 3, 3, 1, 4, 4]
unique_elements, counts = np.unique(test_list, return_counts=True)
res = list(zip(unique_elements, counts))
print("Frequency of list elements : " + str(res))

                    
OUTPUT:
Frequency of list elements : [(1, 2), (3, 2), (4, 2)]

Time complexity: O(nlogn), where n is the length of the input list. 
Auxiliary space: O(n), since we need to create arrays to store the unique elements and their counts.

Method #7: Using collections.defaultdict()

Step-by-Step Approach:

  • Import the defaultdict class from the collections module.
  • Initialize an empty defaultdict with int as its default value.
  • Iterate through the elements of the input list test_list and increment the value of the corresponding key in the defaultdict.
  • Convert the defaultdict to a list of tuples.
  • Sort the list of tuples based on the values in decreasing order.
  • Return the sorted list.

Below is the implementation of the above approach:

Python3

# Python3 code to demonstrate working of
# Frequency grouping of list elements
# using collections.defaultdict()
 
# import defaultdict class from collections module
from collections import defaultdict
 
# initialize list
test_list = [1, 3, 3, 1, 4, 4]
 
# printing original list
print("The original list : " + str(test_list))
 
# Frequency grouping of list elements
# using collections.defaultdict()
freq_dict = defaultdict(int)
for ele in test_list:
    freq_dict[ele] += 1
res = sorted(freq_dict.items(), key=lambda x: x[1], reverse=True)
 
# printing result
print("Frequency of list elements : " + str(res))

                    

Output
The original list : [1, 3, 3, 1, 4, 4]
Frequency of list elements : [(1, 2), (3, 2), (4, 2)]

Time Complexity: O(nlogn), where n is the length of the input list test_list. This is because the sorting step takes O(nlogn) time.
Auxiliary Space: O(n), where n is the length of the input list test_list. This is because we are storing the frequency of each element in a dictionary with at most n keys.



Last Updated : 23 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads