Python Code:
b=['six', 'small', 'he', 'foxes', 'saw']
b.sort(key=len)
b
Output:
['he', 'six', 'saw', 'small', 'foxes']
In the above code, I sorted by length of elements and got the above output.
The output I want looks like this: ['he', 'saw', 'six', 'small', 'foxes']
So I want the first sort by length. Then for elements with the same length I want to sort alphabetically.
My question: Is there a way to do it without writing a custom function? Maybe something like this:
b.sort(key=[len,sorted]) # this doesn't work but I think it explains the idea.
Thanks!
We can use a compound sorting key, first sort by length, second lexicographically. We do this by creating a tuple, because tuples will naturally sort using the elements in the order they appear.
b = ['six', 'small', 'he', 'foxes', 'saw']
b.sort(key=lambda s: (len(s), s))
For the record, the above results in this sorted list::
['he', 'saw', 'six', 'foxes', 'small']
Which is the correct order as stipulated in the question (but the sample output in the question is wrong, so please be aware of it before downvoting!)
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