Check Anagrams in Python
"listen" and "silent" use the same letters. Normalize both words, sort the letters and compare.
- Normalizing case and spaces
- Comparing sorted letters
- Using collections.Counter instead
e i l n s t
e i l n s t
- equal → anagrams
Same letters, different order
The problem
Word games and puzzles ask whether two words use exactly the same letters: "listen" and "silent", "evil" and "vile". Comparing the words directly fails because the order is different, so you need a form that ignores order.
Think of it like this
Checking anagrams is like tipping two bags of letter tiles onto a table and sorting each pile alphabetically. If both sorted piles look identical, the bags held the same letters, whatever word they spelled before.
character.isalpha()🧹 Remove spaces and punctuationcharacter.lower()🔡 Make all tiles the same casesorted(...)🔤 Sort each pile alphabeticallynormalize(first) == normalize(second)⚖️ Are the piles identical?Two words or phrases are anagrams when they contain exactly the same letters the same number of times, in any order.
Key points
normalizekeeps only letters withcharacter.isalpha()and makes them lowercase.sorted(...)puts the letters in alphabetical order, so"listen"and"silent"both become the same list.normalize(first) == normalize(second)compares the two sorted lists.resultholds"are"or"are not"for the final sentence.
When should you use it?
- Word games and puzzles.
- Grouping words that use the same letters.
- Learning to compare things by a normalized form instead of directly.
When not to use it
- Very long texts: counting letters with
Counteravoids sorting and is faster. - Words with accented letters if accents should not matter: remove the accents first.
Example code
def normalize(text):
# Ignore spaces, punctuation, and letter case.
return sorted(character.lower() for character in text if character.isalpha())
first, second = "listen", "silent"
result = "are" if normalize(first) == normalize(second) else "are not"
print(f"{first} and {second} {result} anagrams")
Result of running the code
listen and silent are anagrams
Code explanation
normalize goes through the text, keeps only letters, makes them lowercase and returns them as a sorted list. Calling it on "listen" and on "silent" gives the same list, because both words contain the same letters. The comparison is therefore True and result becomes "are".
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.
Common mistakes
Comparing sets of letters
Sets ignore how often a letter appears, so "aab" and "abb" would match.
set(first) == set(second)
sorted(first) == sorted(second)
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Anagram Check Check whether two phrases use the same letters. Easy
- Pangram Check A pangram contains every English letter at least once. Easy