Python | Identical Strings Grouping
Last Updated :
09 Apr, 2023
Sometimes, we need to perform the conventional task of grouping some like Strings into a separate list and thus forming a list of list. This can also help in counting and also get the sorted order of elements. Let’s discuss certain ways in which this can be done.
Method #1: Using collections.Counter()
This particular function can prove to be quite useful to perform this particular task as it counts the frequency of Strings in the list and then we can pair them using the list comprehension.
Python3
# Python3 code to demonstrate
# Identical Strings Grouping
# using collections.Counter()
import collections
# initializing list
test_list = ["Gfg", "best", "is", "Gfg", "is", "best", "Gfg", "best"]
# printing original list
print("The original list : " + str(test_list))
# using collections.Counter()
# Identical Strings Grouping
temp = collections.Counter(test_list)
res = [[i] * j for i, j in temp.items()]
# print result
print("The Strings after grouping are : " + str(res))
Output : The original list : ['Gfg', 'best', 'is', 'Gfg', 'is', 'best', 'Gfg', 'best']
The Strings after grouping are : [['best', 'best', 'best'], ['Gfg', 'Gfg', 'Gfg'], ['is', 'is']]
The time complexity of the code is O(n), where n is the length of the input list.
The auxiliary space complexity of the code is also O(n), as the space required for the Counter object and the resulting list both depend on the number of unique strings in the input list, which can be at most n.
Method #2: Using itertools.groupby()
This problem can easily solved by the traditional groupby functionality that is offered by Python via groupby function, which groups the like elements as suggested by name.
Python3
# Python3 code to demonstrate
# Identical Strings Grouping
# using itertools.groupby()
import itertools
# initializing list
test_list = ["Gfg", "best", "is", "Gfg", "is", "best", "Gfg", "best"]
# printing original list
print("The original list : " + str(test_list))
# using itertools.groupby()
# Identical Strings Grouping
res = [list(i) for j, i in itertools.groupby(sorted(test_list))]
# print result
print("The Strings after grouping are : " + str(res))
Output : The original list : ['Gfg', 'best', 'is', 'Gfg', 'is', 'best', 'Gfg', 'best']
The Strings after grouping are : [['best', 'best', 'best'], ['Gfg', 'Gfg', 'Gfg'], ['is', 'is']]
Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Time complexity: The time complexity of this code is O(nlogn), where n is the length of the input list test_list.
Auxiliary space: The auxiliary space used by this code is O(n), where n is the length of the input list test_list.
Method #3 : Using count() method
Python3
# Python3 code to demonstrate
# Identical Strings Grouping
# initializing list
test_list = ["Gfg", "best", "is", "Gfg", "is", "best", "Gfg", "best"]
# printing original list
print("The original list : " + str(test_list))
res=[]
x=list(set(test_list))
x.sort()
for i in x:
a=[i]*test_list.count(i)
res.append(a)
# print result
print("The Strings after grouping are : " + str(res))
OutputThe original list : ['Gfg', 'best', 'is', 'Gfg', 'is', 'best', 'Gfg', 'best']
The Strings after grouping are : [['Gfg', 'Gfg', 'Gfg'], ['best', 'best', 'best'], ['is', 'is']]
Method #4 : Using operator.countOf() method
Python3
# Python3 code to demonstrate
# Identical Strings Grouping
# initializing list
test_list = ["Gfg", "best", "is", "Gfg", "is", "best", "Gfg", "best"]
# printing original list
print("The original list : " + str(test_list))
res=[]
x=list(set(test_list))
x.sort()
import operator
for i in x:
a=[i]*operator.countOf(test_list,i)
res.append(a)
# print result
print("The Strings after grouping are : " + str(res))
OutputThe original list : ['Gfg', 'best', 'is', 'Gfg', 'is', 'best', 'Gfg', 'best']
The Strings after grouping are : [['Gfg', 'Gfg', 'Gfg'], ['best', 'best', 'best'], ['is', 'is']]
Time Complexity : O(N)
Auxiliary Space : O(N)
METHOD 5: using a dictionary to group identical strings:
This method creates an empty dictionary res and iterates over the elements of the test_list. For each element s, it checks if it already exists in the dictionary. If it does, it appends s to the list corresponding to the key s. If it doesn't, it creates a new list with s as its only element and assigns it to the key s in the dictionary. Finally, it converts the dictionary values to a list and prints the result.
Python3
# Python3 code to demonstrate
# Identical Strings Grouping
# initializing list
test_list = ["Gfg", "best", "is", "Gfg", "is", "best", "Gfg", "best"]
# printing original list
print("The original list : " + str(test_list))
# using dictionary to group identical strings
res = {}
for s in test_list:
if s in res:
res[s].append(s)
else:
res[s] = [s]
# converting dictionary values to list
res = list(res.values())
# print result
print("The Strings after grouping are : " + str(res))
OutputThe original list : ['Gfg', 'best', 'is', 'Gfg', 'is', 'best', 'Gfg', 'best']
The Strings after grouping are : [['Gfg', 'Gfg', 'Gfg'], ['best', 'best', 'best'], ['is', 'is']]
The time complexity of the above Python code is O(n), where n is the length of the input list test_list
The auxiliary space complexity of the code is O(k), where k is the number of unique elements in the input list.
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