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
# 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))
OutputThe 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))
OutputThe 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))
OutputThe 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))
OutputThe 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))
OutputFrequency 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))
OutputThe 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