Python | Split list of strings into sublists based on length

09 Mar, 2022
Given a list of strings, write a Python program to split the list into sublists based on string length.Examples:  
Input : ['The', 'art', 'of', 'programming']
Output : [['of'], ['The', 'art'], ['programming']]

Input : ['Welcome', 'to', 'geeksforgeeks']
Output : [['to'], ['Welcome'], ['geeksforgeeks']]
Approach #1 : Pythonic naiveA naive approach for the above method uses a dictionary and a for loop to traverse the list. In each iteration, it checks whether the element length is already in the list or not. If not, it adds the element length and element as key:value pair, otherwise, the element is just added to the value sublist. Finally, we make a list of all the values of the dict and return it. 
Python3
# Python3 program to Divide list of strings# into sublists based on string length def divideList(lst):    dct = {}     for element in lst:        if len(element) not in dct:            dct[len(element)] = [element]        elif len(element) in dct:            dct[len(element)] += [element]         res = []    for key in sorted(dct):        res.append(dct[key])         return res     # Driver codelst = ['The', 'art', 'of', 'programming']print(divideList(lst))
[['of'], ['The', 'art'], ['programming']]
 
  Approach #2 : defaultdict() from collections moduleThis method uses defaultdict and saves it in a variable ‘group_by_len’. Using a for loop, we save the length of string as key and the string with the key length as its value. Finally, we make a list of all the values of ‘group_by_len’ and return it.  
Python3
# Python3 program to Divide list of strings# into sublists based on string lengthfrom collections import defaultdict def divideList(lst):    group_by_len = defaultdict(list)    for ele in lst:        group_by_len[len(ele)].append(ele)             res = []    for key in sorted(group_by_len):        res.append(group_by_len[key])             return res     # Driver codelst = ['The', 'art', 'of', 'programming']print(divideList(lst))
[['of'], ['The', 'art'], ['programming']]
 
  Approach #3 : groupby() from itertools moduleThe most efficient and simplest method to solve the given problem is using groupby() from itertools module. This is a one-liner where we use two variables ‘l'(for length) and ‘g'(group of strings) to traverse through ‘lst’, grouped by length and finally return all groups packed within a list.  
Python3
# Python3 program to Divide list of strings# into sub lists based on string lengthfrom itertools import groupby def divideList(lst):    res = dict((l, list(g)) for l, g in groupby(lst, key = len))     # Sorting dict by key    res = sorted(res.items(), key = lambda kv:(kv[0], kv[1]))     # Removing key from list of tuple    return [el[1:] for el in (tuple(x) for x in res)]     # Driver codelst = ['The', 'art', 'of', 'programming']print(divideList(lst))
[(['of'],), (['The', 'art'],), (['programming'],)]
 
varshagumber28
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers