Python | Frequency grouping of list elements
Last Updated :
23 Mar, 2023
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
test_list = [ 1 , 3 , 3 , 1 , 4 , 4 ]
print ( "The original list : " + str (test_list))
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]))
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
from collections import Counter
test_list = [ 1 , 3 , 3 , 1 , 4 , 4 ]
print ( "The original list : " + str (test_list))
res = list (Counter(test_list).items())
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
test_list = [ 1 , 3 , 3 , 1 , 4 , 4 ]
print ( "The original list : " + str (test_list))
res = []
x = list ( set (test_list))
for i in x:
res.append((i, test_list.count(i)))
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
import operator as op
test_list = [ 1 , 3 , 3 , 1 , 4 , 4 ]
print ( "The original list : " + str (test_list))
res = []
x = list ( set (test_list))
for i in x:
res.append((i, op.countOf(test_list,i)))
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
from collections import defaultdict
test_list = [ 1 , 3 , 3 , 1 , 4 , 4 ]
print ( "The original list : " + str (test_list))
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 )
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.
Similar Reads
Python - List Frequency of Elements
We are given a list we need to count frequencies of all elements in given list. For example, n = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] we need to count frequencies so that output should be {4: 4, 3: 3, 2: 2, 1: 1}. Using collections.Countercollections.Counter class provides a dictionary-like structure that
2 min read
Python | Group list elements based on frequency
Given a list of elements, write a Python program to group list elements and their respective frequency within a tuple. Examples: Input : [1, 3, 4, 4, 1, 5, 3, 1] Output : [(1, 3), (3, 2), (4, 2), (5, 1)] Input : ['x', 'a', 'x', 'y', 'a', 'x'] Output : [('x', 3), ('a', 2), ('y', 1)] Method #1: List c
5 min read
Python - Step Frequency of elements in List
Sometimes, while working with Python, we can have a problem in which we need to compute frequency in list. This is quite common problem and can have usecase in many domains. But we can atimes have problem in which we need incremental count of elements in list. Let's discuss certain ways in which thi
4 min read
Frequency of Elements from Other List - Python
We are given a list of elements and another list containing specific values and our task is to count the occurrences of these specific values in the first list "a" and return their frequencies. For example: a = [1, 2, 2, 3, 4, 2, 5, 3, 1], b = [1, 2, 3]. Here b contains the elements whose frequency
3 min read
Python - Fractional Frequency of elements in List
Given a List, get fractional frequency of each element at each position. Input : test_list = [4, 5, 4, 6, 7, 5, 4, 5, 4] Output : ['1/4', '1/3', '2/4', '1/1', '1/1', '2/3', '3/4', '3/3', '4/4'] Explanation : 4 occurs 1/4th of total occurrences till 1st index, and so on.Input : test_list = [4, 5, 4,
5 min read
Python - Restrict Elements Frequency in List
Given a List, and elements frequency list, restrict frequency of elements in list from frequency list. Input : test_list = [1, 4, 5, 4, 1, 4, 4, 5, 5, 6], restrct_dict = {4 : 3, 1 : 1, 6 : 1, 5 : 1} Output : [1, 4, 5, 4, 4, 6] Explanation : Limit of 1 is 1, any occurrence more than that is removed.
5 min read
Python - Elements frequency count in multiple lists
Sometimes while working with Python lists we can have a problem in which we need to extract the frequency of elements in list. But this can be added work if we have more than 1 list we work on. Let's discuss certain ways in which this task can be performed. Method #1: Using dictionary comprehension
6 min read
Python | Sort list elements by frequency
Our task is to sort the list based on the frequency of each element. In this sorting process, elements that appear more frequently will be placed before those with lower frequency. For example, if we have: a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"] then the output should be: ['Aryan'
3 min read
Python | Find most frequent element in a list
Given a list, find the most frequent element in it. If multiple elements appear a maximum number of times, print any one of them using Python. Example Make a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we
2 min read
Python - List Elements Grouping in Matrix
Given a Matrix, for groups according to list elements, i.e each group should contain all elements from List. Input : test_list = [[2, 6], [7, 8], [1, 4]], check_list = [1, 2, 4, 6] Output : [[7, 8], [[1, 2], [4, 6]]] Explanation : 1, 2, 4, 6 elements rows are grouped. Input : test_list = [[2, 7], [7
8 min read