Python | Split list of strings into sublists based on length

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 naive



A 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 code
lst = ['The', 'art', 'of', 'programming']
print(divideList(lst))

chevron_right


Output:

[['of'], ['The', 'art'], ['programming']]

 
Approach #2 : defaultdict() from collections module

This 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Divide list of strings 
# into sublists based on string length
from 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 code
lst = ['The', 'art', 'of', 'programming']
print(divideList(lst))

chevron_right


Output:

[['of'], ['The', 'art'], ['programming']]

 
Approach #3 : groupby() from itertools module

The 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 vaiables ‘l'(for length) and ‘g'(group of strings) to traverse through ‘lst’, grouped by length and finally return all groups packed within a list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Divide list of strings 
# into sub lists based on string length
from 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 code
lst = ['The', 'art', 'of', 'programming']
print(divideList(lst))

chevron_right


Output:

[(['of'],), (['The', 'art'],), (['programming'],)]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.