# Python: sort a list of sublists by the total number of elements in them

I want to sort a list of sublists in ascending order. The sublists should be sorted by the number of their elements, i.e., if a list has 2 elements and another list has 4 elements, the list with 2 elements should come first.

How to do this in Python?

by (33.7k points)
edited by

The argsort() function of Numpy can be used. You can sort the indices of sublists by using the length of sublists as an argument of the argsort() function. You can then use the sorted indices to sort the list of sublists.

Here is an example:

Let's generate a list of sublists with different lengths:

>>> import numpy as np
>>> import random
>>> a=[[random.randint(10,45) for _ in range(4)]]
>>> a.append([random.randint(10,90) for _ in range(8)])
>>> a.append([random.randint(10,90) for _ in range(5)])
>>> a.append([random.randint(10,90) for _ in range(9)])
>>> a.append([random.randint(10,90) for _ in range(3)])
>>> a
[[14, 14, 11, 19], [85, 52], [82, 80, 45, 33, 73, 34, 84, 37], [86, 77, 67, 25, 79], [66, 45, 58, 28, 53, 51, 48, 34, 39], [83, 15, 29]]

Now, create a list of the length of sublists and use the argsort() function to sort the indices by length.

>>> counts = [len(v) for v in a]
>>> counts
[4, 2, 8, 5, 9, 3]
>>> i=np.argsort(counts)
>>> i
array([1, 5, 0, 3, 2, 4])

Now, you can use the sorted indices to sort the list of lists.

>>> list(np.array(a)[i])
[[85, 52], [83, 15, 29], [14, 14, 11, 19], [86, 77, 67, 25, 79], [82, 80, 45, 33, 73, 34, 84, 37], [66, 45, 58, 28, 53, 51, 48, 34, 39]]