Python Categorize the given list by string size


Let's consider a list containing many strings of different lengths. In this article we will see how to club those elements into groups where the strings are of equal length in each group.

With for loop

We design a for loop which will iterate through every element of the list and happened it only to the list where its length matches with the length of existing element.

Example

 Live Demo

listA = ['Monday','Thursday','Friday','Saturday','Sunday']
# Given list
print("Given list : \n",listA)
# Categorize by string size
len_comp = lambda x, y: len(x) == len(y)
res = []
for sub_list in listA:
   ele = next((i for i in res if len_comp(sub_list, i[0])), [])
   if ele == []:
      res.append(ele)
   ele.append(sub_list)
# Result
print("The list after creating categories : \n",res)

Output

Running the above code gives us the following result −

Given list :
['Monday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
The list after creating categories :
[['Monday', 'Friday', 'Sunday'], ['Thursday', 'Saturday']]

With sort and groupby

In this approach we first shot all the elements as per their length and then apply the group by function which is part of itertools module.

Example

 Live Demo

from itertools import groupby
listA = ['Monday','Thursday','Friday','Saturday','Sunday']
# Given list
print("Given list : \n",listA)
# Categorize by string size
get_len = lambda x: len(x)
sub_list = sorted(listA, key = get_len)
res = [list(ele) for i, ele in groupby(sub_list, get_len)]
# Result
print("The list after creating categories : \n",res)

Output

Running the above code gives us the following result −

Given list :
['Monday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
The list after creating categories :
[['Monday', 'Friday', 'Sunday'], ['Thursday', 'Saturday']]

Updated on: 09-Jul-2020

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements