Editor

Python Program to Sort Words in Alphabetical Order

Beginner · Strings

This program takes a sentence, splits it into words and puts the words in alphabetical (dictionary) order. Python compares strings using character codes, in which every capital letter comes before every small letter, so the program changes the words to lower case first.

Program

sort_words_alphabetically.py
text = "Learning Python is fun and Easy" # or: text = input("Enter a sentence: ")
# Lower case first, because "Z" sorts before "a" in Python
words = text.lower().split()
words.sort()
print("Sentence:", text)
print("Sorted words:", words)
print("As a sentence:", " ".join(words))
Output
Sentence: Learning Python is fun and Easy
Sorted words: ['and', 'easy', 'fun', 'is', 'learning', 'python']
As a sentence: and easy fun is learning python

How it works

  1. text.lower() makes every letter small, and split() turns the sentence into a list of words.
  2. words.sort() arranges the list in place, from a to z.
  3. Strings are compared character by character using their codes, and capital letters have smaller codes than small letters, which is why lower-casing first matters.
  4. " ".join(words) joins the sorted words back into one string with spaces between them.

Other ways to write it

Keeping the original capitals

Keeping the original capitals
text = "Learning Python is fun and Easy"
words = text.split()
print("Plain sorted():", sorted(words))
print("Ignoring case: ", sorted(words, key=str.lower))
print("Z to A: ", sorted(words, key=str.lower, reverse=True))
Output
Plain sorted(): ['Easy', 'Learning', 'Python', 'and', 'fun', 'is']
Ignoring case:  ['and', 'Easy', 'fun', 'is', 'Learning', 'Python']
Z to A:         ['Python', 'Learning', 'is', 'fun', 'Easy', 'and']

key=str.lower compares the lower-case version of each word but keeps the word as written, and reverse=True gives z to a. sorted() returns a new list and leaves words unchanged.

Without sort(): bubble sort

Without sort(): bubble sort
words = ["mango", "apple", "kiwi", "banana", "cherry"]
# Swap neighbours that are in the wrong order, again and again
n = len(words)
for i in range(n - 1):
for j in range(n - 1 - i):
if words[j] > words[j + 1]:
words[j], words[j + 1] = words[j + 1], words[j]
print("Sorted words:", words)
Output
Sorted words: ['apple', 'banana', 'cherry', 'kiwi', 'mango']

Strings can be compared with > just like numbers, so a bubble sort works on words too: it keeps swapping neighbours until the whole list is in order.

Try it yourself

Sort the words by length instead, using sorted(words, key=len).

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