# How To Split A Sorted List By Element Length

## 12 April 2019 - 1 answer

I have a list of lists and it is sorted by the length of the children lists. e.g.

``````[[str], [str1, str2], [str1, str2], [str1, str2, str3], [str1, str2, str3],...]
``````

I would like to split this list into sublists that only contain the children with the same length. e.g.

``````[[[str], [str], [str]],  [[str1, str2], [str1, str2], [str1, str2]], ...]
``````

I was wondering if there is a more efficient approach than mine below with hopefully a little less code.

``````child_list = []
new_list = []
old_list = [['e3510000'], ['e2512001'], ['e3510000'], ['e92d4010'],
['e3a0b000', 'e3a0e000'], ['e92d4030', 'e59f5054'],
['e59f3038', 'e3530000'], ['e1a0c00d', 'e92dd800']]

# length of child
length = 1
for idx, i in enumerate(old_list):
if idx == len(old_list)-1:
child_list.append(i)
new_list.append(child_list.copy())
elif length == len(i):
child_list.append(i)
elif length < len(i):
new_list.append(child_list.copy())
del child_list[:]
child_list.append(i)
length = len(i)
``````

Output:

``````[[['e3510000'], ['e2512001'], ['e3510000'], ['e92d4010']],
[['e3a0b000', 'e3a0e000'], ['e92d4030', 'e59f5054'],
['e59f3038', 'e3530000'], ['e1a0c00d', 'e92dd800']]]
``````

You can use `itertools.groupby` in order to group the lists in `old` by length. Note that if the original lists are already ordered according to their length as in your example, sorting here is not necessary.

``````from itertools import groupby
[list(v) for k,v in groupby(sorted(old_list, key=len), key=len)]
``````

Output

``````[[['e3510000'], ['e2512001'], ['e3510000'], ['e92d4010']],
[['e3a0b000', 'e3a0e000'],
['e92d4030', 'e59f5054'],
['e59f3038', 'e3530000'],
['e1a0c00d', 'e92dd800']]]
``````