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.
# 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)) |
[['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.
# 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)) |
[['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.
# 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)) |
[(['of'],), (['The', 'art'],), (['programming'],)]
Recommended Posts:
- Python | Split a list into sublists of given lengths
- Python | Sort all sublists in given list of strings
- Python | Pandas Split strings into two List/Columns using str.split()
- Python | Filter list of strings based on the substring list
- Python | Filter a list based on the given list of strings
- Python | Split strings in list with same prefix in all elements
- Python | Pandas Reverse split strings into two List/Columns using str.rsplit()
- Python | Print all sublists of a list
- Python | Remove repeated sublists from given list
- Python | Count unique sublists within list
- Python | Count the sublists containing given element in a list
- Python | Sort list of lists by the size of sublists
- Python | Split Sublist Strings
- Python | Reversed Split Strings
- Python | Add list elements with a multi-list based on index
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.



