Editor

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

sort_strings_by_length.py
words = ["kiwi", "banana", "fig", "plum", "cherry", "apple", "date"]
# len() of each word decides the order
by_length = sorted(words, key=len)
print("Words:", words)
print("Shortest to longest:", by_length)
print("Longest to shortest:", sorted(words, key=len, reverse=True))
# Same length? Sort by length first, then alphabetically
print("By length, then A to Z:", sorted(words, key=lambda w: (len(w), w)))
for word in by_length:
print(f" {word:<7} {len(word)} letters")
Output
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

  1. key=len makes sorted() call len() on every word and sort by those numbers.
  2. 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.
  3. reverse=True puts the longest words first.
  4. 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

Without key, using bubble sort
words = ["kiwi", "banana", "fig", "plum", "cherry"]
n = len(words)
for i in range(n - 1):
for j in range(n - 1 - i):
if len(words[j]) > len(words[j + 1]): # compare lengths, not letters
words[j], words[j + 1] = words[j + 1], words[j]
print("Shortest to longest:", words)
Output
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

Sort the words of a sentence
sentence = "Python makes learning to code fun"
words = sentence.split()
words.sort(key=len)
print("Words by length:", " ".join(words))
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises