utij2004
utij2004

Reputation: 453

Sort a list of lists by length and value in Python

How can I sort a Python list (with sublists)? For example, I have the following list:

list1 = [[0, 4, 1, 5], [3, 1, 5], [4, 0, 1, 5]]

After sorting I am expecting:

list1 = [[3, 1, 5], [0, 4, 1, 5], [4, 0, 1, 5]]

Another example. I have the following list:

list2 = [[4, 5, 2], [2, 5, 4], [2, 4, 5]]

After sorting I am expecting:

list2 = [[2, 4, 5], [2, 5, 4], [4, 5, 2]]

At first I want to sort by length, and then by itemwise in each sublist. I do not want to sort any sublist.

I have tried the following code, which helped me to sort by length only:

list1.sort(key=len)

Upvotes: 18

Views: 6076

Answers (2)

Peter Otten
Peter Otten

Reputation: 424

Python's list.sort() method is "stable", i. e. the relative order of items that compare equal does not change. Therefore you can also achieve the desired order by calling sort() twice:

>>> list1 = [[3, 1, 5], [0, 4, 1, 5], [4, 0, 1, 5]]
>>> list1.sort()  # sort by sublist contents
>>> list1.sort(key=len)  # sort by sublist length
>>> list1
[[3, 1, 5], [0, 4, 1, 5], [4, 0, 1, 5]]

Upvotes: 0

Stephen Rauch
Stephen Rauch

Reputation: 49832

You need a key like:

lambda l: (len(l), l)

How:

This uses a lambda to create a tuple which can the be used by sorted to sort in the desired fashion. This works because tuples sort element by element.

Test Code:

list1 = [[0, 4, 1, 5], [3, 1, 5], [4, 0, 1, 5]]
print(sorted(list1, key=lambda l: (len(l), l)))

list2 = [[4, 5, 2], [2, 5, 4], [2, 4, 5]]
print(sorted(list2, key=lambda l: (len(l), l)))

Results:

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

Upvotes: 42

Related Questions