Two words are anagrams if you can make one from the other by rearranging its letters. For example, ‘listen’ and ‘silent’ use exactly the same letters, so they are anagrams. In this lesson you will write a Python program to check an anagram in three ways: by sorting, with Counter, and with a manual count. You will also handle capital letters and spaces.
Run the code in our online Python compiler. The compiler does not take keyboard input, so the examples use fixed values.
The logic
Two strings are anagrams when they contain the same letters the same number of times. There are two simple ways to check:
- Sort the letters of both strings. If the sorted results are equal, the strings are anagrams.
- Count how often each letter appears in both strings. If the counts match, they are anagrams.
Method 1: sort and compare
def is_anagram(a, b):
return sorted(a.lower()) == sorted(b.lower())
print(is_anagram('listen', 'silent'))
print(is_anagram('hello', 'world'))
print(is_anagram('Dormitory', 'Dirty room'))Output:
True
False
Falsesorted() turns a string into a sorted list of its letters:
print(sorted('listen'))
print(''.join(sorted('silent')))
['e', 'i', 'l', 'n', 's', 't']
eilnstBoth ‘listen’ and ‘silent’ give the same list of letters, so they are anagrams.
The lower() call makes the check case-insensitive. Without it, ‘Listen’ and ‘Silent’ would not match, because capital letters sort before small letters:
print(sorted('Listen') == sorted('Silent'))
False
Anagrams with spaces and punctuation
The third example above printed False, but ‘Dormitory’ and ‘Dirty room’ are a famous anagram pair. The space in ‘Dirty room’ is counted as a character. Keep only letters and digits with isalnum():
def is_anagram(a, b):
clean = lambda s: sorted(ch.lower() for ch in s if ch.isalnum())
return clean(a) == clean(b)
print(is_anagram('Dormitory', 'Dirty room'))
print(is_anagram('Astronomer', 'Moon starer'))
print(is_anagram('abc', 'abd'))Output:
True True False
Method 2: using Counter
The Counter class from the collections module counts how many times each item appears. Two strings are anagrams if their counts are equal.
from collections import Counter
print(Counter('listen') == Counter('silent'))
print(Counter('aab') == Counter('abb'))Output:
True
FalseThis method is faster than sorting for long strings, because it does not need to sort.
Method 3: count the letters yourself
This version uses a dictionary, and shows what Counter does inside.
def is_anagram(a, b):
if len(a) != len(b):
return False
counts = {}
for ch in a:
counts[ch] = counts.get(ch, 0) + 1
for ch in b:
if counts.get(ch, 0) == 0:
return False
counts[ch] -= 1
return True
print(is_anagram('listen', 'silent'))
print(is_anagram('aab', 'abb'))
print(is_anagram('abc', 'abcd'))Output:
True
False
FalseThe program counts each letter of the first word, then subtracts one for each letter of the second word. If a letter is missing or used up, the words are not anagrams. If the lengths are different, it returns False straight away.
Which method should you use?
Method | Code length | Best for |
|---|---|---|
sorted() | Shortest | Exams, and most programs |
Counter | Short | Long strings, and when you also need the counts |
Manual dictionary | Longest | Understanding the idea |
Take the words from the user (on your computer)
a = input('Enter the first word: ')
b = input('Enter the second word: ')
if is_anagram(a, b):
print('Anagrams')
else:
print('Not anagrams')Our online compiler does not support input() yet, so use fixed values there.
Common mistakes
- Forgetting lower(). ‘Listen’ and ‘silent’ do not match when the case is different.
- Counting spaces and punctuation. Use isalnum() for sentences.
- Comparing only the lengths, or only the sets of letters. set(‘aab’) and set(‘abb’) are equal, but the words are not anagrams.
- Using sort() on a string. Strings have no sort() method. Use sorted().
Practice questions
- Check whether ‘Triangle’ and ‘Integral’ are anagrams.
- Group the words [‘listen’, ‘silent’, ‘enlist’, ‘google’, ‘gogole’] into anagram groups.
- Check whether a word is an anagram of its reverse.
- Count how many pairs of words in a list are anagrams.
FAQs
What is an anagram?
An anagram is a word or phrase made by rearranging the letters of another word or phrase, using every letter exactly once.
Are ‘listen’ and ‘silent’ anagrams?
Yes. Both use the letters e, i, l, n, s and t once each.
Is a word an anagram of itself?
By the usual definition, yes. The program above returns True for it, unless you add a rule to exclude identical words.
How do I check anagrams without sorting?
Use Counter or the dictionary method. Both count the letters instead of sorting them.
