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']]
Sort the list by passing key to the sort(key = len) method of the list. We have to pass len as key for the sort() method as we are sorting the list based on the length of the string. sort() method will sort the list in place.
You can custom the sort behaviour by pass a key and reverse. sorted will return a new list. If in-place sort wanted, use list. sort .
1. Take in a list containing sublists. 2. Using two for loops, use bubble sort to sort the sublists based on the second value of the sublist.
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With