Python - Sort List of Lists by the Size of Sublists

Last Updated : 28 Jan, 2026

Given a list containing multiple sublists, the task is to sort the main list based on the size (length) of each sublist, either in ascending or descending order.

Example: Sorting a list of lists in ascending order using Python's built-in "sorted" function:

Python
a = [[1, 2], [1], [1, 2, 3]]
asc = sorted(a, key=len)
print(asc)

Output
[[1], [1, 2], [1, 2, 3]]

sorted() function does not sort the original list in-place but it returns a new sorted list. Let's look at the different methods to solve this task.

Reverse Sorting Using sorted()

By giving the reverse parameter as True in sorted() function, we can get a sorted list in descending order:

Python
a = [[1, 2], [1], [1, 2, 3]]
asc = sorted(a, key=len)
des = sorted(a, key=len, reverse=True)
print(asc)
print(des)

Output
[[1], [1, 2], [1, 2, 3]]
[[1, 2, 3], [1, 2], [1]]

Explanation:

  • sorted(a, key=len): sorts sublists by their length.
  • reverse=True: sorts in descending order.
  • sorted(): returns a new sorted list without modifying the original.

Inplace Sorting Using sort()

This method sorts the original list using sort() directly in place based on the length of each sublist in ascending order.

Python
a = [[1, 2], [3, 4, 5], [6]]
a.sort(key=len)
print(a)

Output
[[6], [1, 2], [3, 4, 5]]

Explanation:

  • a.sort(): sorts the original list in place.
  • key=len: ensures sublists are compared based on their lengths in ascending order.

Using List Comprehension and sorted()

This method uses sorted(a, key=len) to arrange the sublists based on their lengths, and list comprehension to collect them into a new list in the same sorted order.

Python
a = [[1, 2], [3, 4, 5], [6]]
res = [sublist for sublist in sorted(a, key=len)]
print(res)

Output
[[6], [1, 2], [3, 4, 5]]

Explanation:

  • sorted(a, key=len): sorts the list by sublist lengths in ascending order.
  • List comprehension collects sublists in the sorted order.

Using For Loop

This method demonstrates manual sorting by repeatedly comparing and swapping sublists using for loop.

Python
a = [[1, 2], [3, 4, 5], [6]]
for i in range(len(a)):
    for j in range(len(a) - i - 1):
        if len(a[j]) > len(a[j + 1]):
            a[j], a[j + 1] = a[j + 1], a[j]

print(a)

Output
[[6], [1, 2], [3, 4, 5]]

Explanation:

  • for i in range(len(a)): outer loop iterates over the list.
  • for j in range(len(a) - i - 1): Inner loop compares adjacent sublists and swaps them if the first is longer, resulting in ascending order.
Comment