How to sort list of lists according to length of sublists

Question:

I have the following list

a = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h'], ['i', 'j', 'k', 'l'], ['m', 'n'], ['o']]

I would like to sort the list based on the length of their sub lists.
The result should be like:

a = [['o'],['d','e'],['m', 'n'],['a', 'b', 'c'],['f', 'g', 'h'], ['i','j','k','l']]
Asked By: rajeshv90

||

Answers:

Use key parameter available in sort and sorted. It specifies a function of one argument that is used to extract a comparison key from each list element

In [6]: a = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h'], ['i', 'j', 'k', 'l'], ['m', 'n'], ['o']]

In [7]: a.sort(key=len)

In [8]: print a
[['o'], ['d', 'e'], ['m', 'n'], ['a', 'b', 'c'], ['f', 'g', 'h'], ['i', 'j', 'k', 'l']]
Answered By: Konstantin

can be done by

sorted(a, key=len)
Answered By: sachin saxena
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.