Python Sort list of lists by the size of sublists (original) (raw)

Last Updated : 17 Jan, 2025

The problem is to sort a list of lists based on the size of each sublist. For example, given the list [[1, 2], [1], [1, 2, 3]], the sorted result should be [[1], [1, 2], [1, 2, 3]] when sorted in ascending order. We will explore multiple methods to do this in Python.

Using sorted() with len()

This method uses Python's built-in sorted() function, which allows us to specify a custom key for sorting. Here, we use the length of each sublist as the key.

Python `

Input list of lists

a = [[1, 2], [1], [1, 2, 3]]

Sort based on sublist size

result = sorted(a, key=len) print(result)

`

Output

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

**Explanation:

Let's explore some more ways and see how we can sort list of lists by the size of sublists.

Table of Content

Using sort() with len()

If we want to sort the list in place without creating a new list, we can use the sort() method.

Python `

Input list of lists

a = [[1, 2], [3, 4, 5], [6]]

Sort the list in place by the size of the sublists

a.sort(key=len) print(a)

`

Output

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

**Explanation:

Using List Comprehension and sorted()

We can use a combination of list comprehension and sorted() to sort the list and explicitly display the sizes of the sublists for better understanding.

Python `

Input list of lists

a = [[1, 2], [3, 4, 5], [6]]

Sort the list in place by the size of the sublists

a.sort(key=len) print(a)

`

Output

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

**Explanation:

Using For Loop

This is a more manual approach which involves iterating through the list and sorting it manually using a simple for loop.

Python `

Input list of lists

a = [[1, 2], [3, 4, 5], [6]]

Sort the list manually using a nested loop

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: This method uses a bubble sort algorithm, comparing adjacent sublists and swapping them based on their size.

Similar Reads