Python Program to Sort Strings by Length
Beginner · Searching and sorting
By default Python sorts strings alphabetically. Passing key=len makes it sort them by their number of characters instead, from shortest to longest. This program also shows how to put words of the same length in alphabetical order.
Program
Words: ['kiwi', 'banana', 'fig', 'plum', 'cherry', 'apple', 'date'] Shortest to longest: ['fig', 'kiwi', 'plum', 'date', 'apple', 'banana', 'cherry'] Longest to shortest: ['banana', 'cherry', 'apple', 'kiwi', 'plum', 'date', 'fig'] By length, then A to Z: ['fig', 'date', 'kiwi', 'plum', 'apple', 'banana', 'cherry'] fig 3 letters kiwi 4 letters plum 4 letters date 4 letters apple 5 letters banana 6 letters cherry 6 letters
How it works
key=lenmakessorted()calllen()on every word and sort by those numbers.- Words with the same length keep their original order, because Python sorts stably: kiwi, plum and date all have 4 letters and stay in that order.
reverse=Trueputs the longest words first.- The key
lambda w: (len(w), w)returns a tuple, so words are compared by length first and alphabetically when the lengths are equal, giving date, kiwi, plum.
Other ways to write it
Without key, using bubble sort
Shortest to longest: ['fig', 'kiwi', 'plum', 'banana', 'cherry']
The usual bubble sort works here too, as long as it compares len() of the words instead of the words themselves.
Sort the words of a sentence
Words by length: to fun code makes Python learning
split() breaks the sentence into words, sort(key=len) orders them in place, and join() puts the sentence back together.
Try it yourself
Change the main program to sort the words by their last letter, using key=lambda w: w[-1].
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises