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 Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read