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
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
text.lower()makes every letter small, andsplit()turns the sentence into a list of words.words.sort()arranges the list in place, from a to z.- 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.
" ".join(words)joins the sorted words back into one string with spaces between them.
Other ways to write it
Keeping the original capitals
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises