PythonMastery
Python programs · Strings · beginner

Sort words in alphabetical order in Python

Split a sentence into words and sort them in alphabetical order, ignore capital letters with key=str.lower, and list each word only once.

split() turns a sentence into a list of words, and sorted() puts the list in alphabetical order. " ".join() turns the list back into one string.

The program

python
sentence = input("Enter a sentence: ")
words = sentence.split()

print("Default:    ", " ".join(sorted(words)))
print("Ignore case:", " ".join(sorted(words, key=str.lower)))

Typed in this example: Python was created by Guido van Rossum and released in 1991. Press Run to type your own.

output
Enter a sentence: Python was created by Guido van Rossum and released in 1991
Default:     1991 Guido Python Rossum and by created in released van was
Ignore case: 1991 and by created Guido in Python released Rossum van was

How it works

Each word only once

A set keeps only one copy of each item. Make the words lower case first, so "The" and "the" count as the same word:

python
sentence = "the cat and The dog and the bird"

words = sentence.lower().split()
unique = sorted(set(words))

print(unique)
print(" ".join(unique))
print(len(words), "words,", len(unique), "different")
output
['and', 'bird', 'cat', 'dog', 'the']
and bird cat dog the
8 words, 5 different

sorted() accepts a set and returns a list, so the order is fixed again after the set. For more about sorted(), sort() and the key argument, see sort a list.

Learn the idea: Working with Strings, Lists & Sequences, Sets: Unordered, Unique, Lightning Fast