Python | Group list elements based on frequency
Last Updated :
28 Mar, 2023
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 comprehension We can use list comprehension to form tuples of each element and the count of its occurrence and store it in 'res', but that will contain the duplicate first element. Thus, to remove the duplicate first element, we use OrderedDict(res).items().
Python3
# Python3 program to Grouping list
# elements based on frequency
from collections import OrderedDict
def group_list(lst):
res = [(el, lst.count(el)) for el in lst]
return list(OrderedDict(res).items())
# Driver code
lst = [1, 3, 4, 4, 1, 5, 3, 1]
print(group_list(lst))
Output:[(1, 3), (3, 2), (4, 2), (5, 1)]
Time Complexity: O(n^2) as we are using two for loops to count the frequency of each element in the list and store it in a new list.
Auxiliary Space: O(n) as we are using an additional list to store the frequency of each element in the original list.
Method #2: Using collections.Counter() collections.Counter() provides two direct methods keys() and values() that provides the elements and its occurrences. At last, zip them together using Python zip() method.
Python3
# Python3 program to Grouping list
# elements based on frequency
from collections import Counter
def group_list(lst):
return list(zip(Counter(lst).keys(), Counter(lst).values()))
# Driver code
lst = [1, 3, 4, 4, 1, 5, 3, 1]
print(group_list(lst))
Output:[(1, 3), (3, 2), (4, 2), (5, 1)]
The time complexity of the group_list() function is O(n), where n is the length of the input list.
The space complexity of the group_list() function is O(k), where k is the number of unique elements in the input list.
Method #3: Using itertools.groupby()
This method uses the itertools.groupby() function to group the elements of the list by their value, and then uses a list comprehension to create a list of tuples containing each element and the length of its group (i.e. its frequency).
Python3
from itertools import groupby
def group_list(lst):
return [(el, len(list(group))) for el, group in groupby(sorted(lst))]
lst = [1, 3, 4, 4, 1, 5, 3, 1]
print(group_list(lst))
#This code is contributed by Edula Vinay Kumar Reddy
Output[(1, 3), (3, 2), (4, 2), (5, 1)]
Time complexity: O(nlogn)
Auxiliary Space: O(n)
Method #4: Using dictionary
We can also solve the problem by using a dictionary to keep track of the frequency of each element. We can iterate through the list and for each element, we check if it's already in the dictionary. If it is, we increment its value by 1, otherwise, we add it to the dictionary with a value of 1. Finally, we can create a list of tuples from the dictionary's items.
Step-by-step approach:
- Initialize an empty dictionary called freq_dict to keep track of the frequency of each element in the list.
- Iterate through the elements in the list
- For each element, check if it's already in freq_dict.
- If it is, increment its value by 1.
- If it's not, add it to the dictionary with a value of 1.
- Create a list of tuples from the dictionary's items using the items() method.
- Sort the list of tuples in descending order based on the frequency of the elements.
- Return the sorted list of tuples.
Below is the implementation of the above approach:
Python3
def group_list(lst):
freq_dict = {}
for el in lst:
if el in freq_dict:
freq_dict[el] += 1
else:
freq_dict[el] = 1
res = list(freq_dict.items())
res.sort(key=lambda x: x[1], reverse=True)
return res
lst = [1, 3, 4, 4, 1, 5, 3, 1]
print(group_list(lst))
Output[(1, 3), (3, 2), (4, 2), (5, 1)]
Time complexity: O(n*logn) due to the sorting step. The dictionary operations take O(1) time.
Auxiliary space: O(n) to store the dictionary.
Method #5: Using set() and count()
Steps:
- Define a function called "group_list" that takes a list "lst" as input.
- Create an empty list called "result" to store the grouped elements.
- Create a set of unique elements in the input list "lst" using the "set" function.
- Use a for loop to iterate over each element in the set.
- Use the "count" method to count the number of occurrences of the current element in the input list "lst".
- Append a tuple of the current element and its frequency to the "result" list using the "append" method.
- Once all the elements in the set have been processed, return the "result" list.
- Define the input list "lst".
- Call the "group_list" function with the "lst" argument and store the result in "grouped_list".
- Print the "grouped_list" using the "print" statement.
Python3
def group_list(lst):
result = []
unique_elements = set(lst)
for ele in unique_elements:
frequency = lst.count(ele)
result.append((ele, frequency))
return result
# Driver code
lst = [1, 3, 4, 4, 1, 5, 3, 1]
grouped_list = group_list(lst)
print(grouped_list)
Output[(1, 3), (3, 2), (4, 2), (5, 1)]
Time complexity: O(n^2) where n is the length of the input list "lst" as we need to count the occurrences of each unique element in the list.
Auxiliary space: O(n) as we need to store the frequencies of all unique elements in the input list in the result list.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â 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.Python is:A high-level language, used in web development, data science, automatio
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
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
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
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
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