Python Anagram Program: Check if Two Strings Are Anagrams
sorted(a) == sorted(b) after lowercasing and removing spaces."Listen" and "silent" use exactly the same letters in a different order, so they are anagrams. Checking this is a popular exercise because it forces you to think about what "same letters" means: order does not matter, but the number of each letter does.
The simplest solution sorts both strings and compares them. A second solution counts letters with a dictionary or Counter, which is faster for long inputs. Both are shown below.
| Input | Two strings |
|---|---|
| Output | True if they are anagrams, otherwise False |
| Approach | Clean both strings, then compare sorted letters or letter counts |
| Time complexity | O(n log n) with sorting, O(n) with counting |
Approach to check for anagrams step by step
- Clean each string: lowercase it and remove spaces so "Dormitory" and "dirty room" can match.
- Compare lengths quickly. Different lengths can never be anagrams.
- Sort the letters of each string with
sorted(), which returns a list of characters. - Compare the two sorted lists with
==.
If both lists are equal, every letter appears the same number of times in both strings.
How the anagram code works
sorted("listen") returns ["e", "i", "l", "n", "s", "t"], and sorted("silent") returns the very same list, so == gives True. We do not need to join the lists back into strings because lists compare element by element.
The cleaning step uses a small helper so the same rule is applied to both inputs. Keeping it in one function avoids the bug where one string is lowercased and the other is not.
def clean(text):
return text.replace(" ", "").lower()
print(sorted(clean("Dormitory")))
print(sorted(clean("dirty room")))Counting letters instead of sorting
collections.Counter turns a string into a mapping of letter to count, and two Counter objects are equal when all their counts match. This takes one pass over each string, so it is O(n) instead of O(n log n). For short words the difference is invisible; choose whichever you find more readable. Learn more about it in Python collections.
| Method | Time | Notes |
|---|---|---|
sorted(a) == sorted(b) | O(n log n) | Shortest and easiest to remember |
Counter(a) == Counter(b) | O(n) | Best for long strings |
| Manual dictionary of counts | O(n) | Shows how counting works |
Examples you can run
Press Run, then edit the code and run it again.
Anagram check with sorted()
Clean both strings, then compare their sorted letters.
def is_anagram(a, b):
a = a.replace(" ", "").lower()
b = b.replace(" ", "").lower()
return sorted(a) == sorted(b)
print(is_anagram("Listen", "Silent"))
print(is_anagram("Dormitory", "dirty room"))
print(is_anagram("apple", "papel"))
print(is_anagram("apple", "pale"))Expected outputTrue
True
True
False
Anagram check with Counter
Counter compares letter counts and never sorts.
from collections import Counter
def is_anagram(a, b):
a = a.replace(" ", "").lower()
b = b.replace(" ", "").lower()
return Counter(a) == Counter(b)
print(is_anagram("night", "thing"))
print(is_anagram("aab", "abb"))Expected outputTrue
False
Edge cases: empty strings and repeated letters
Two empty strings are anagrams of each other; the same letters with different counts are not.
def is_anagram(a, b):
return sorted(a.lower()) == sorted(b.lower())
print(is_anagram("", ""))
print(is_anagram("a", "A"))
print(is_anagram("aabb", "abbb"))Expected outputTrue
True
False
Interactive anagram checker
Ask for two words and print a message.
first = input("First word: ")
second = input("Second word: ")
if sorted(first.lower()) == sorted(second.lower()):
print("Anagrams!")
else:
print("Not anagrams.")Expected outputFirst word: Evil
Second word: Vile
Anagrams!
Common mistakes
Comparing sets instead of sorted letters
✗ Wrong
a, b = "aab", "abb"
print(set(a) == set(b))✓ Right
a, b = "aab", "abb"
print(sorted(a) == sorted(b))A set drops duplicates, so it loses the letter counts. Use sorted() or Counter to keep them.
Forgetting to normalise case
✗ Wrong
print(sorted("Listen") == sorted("Silent"))✓ Right
print(sorted("Listen".lower()) == sorted("Silent".lower()))Lowercase both strings before sorting.
Python Anagram Program: Check if Two Strings Are Anagrams: questions people ask
How do I check if two strings are anagrams in Python?
Lowercase both strings, remove spaces and compare sorted(a) == sorted(b). You can also compare Counter(a) == Counter(b).
Is sorting or Counter better for anagrams?
Counter is faster for long strings because it is O(n), while sorting is O(n log n). For short words, sorted() is shorter and just as good.
Do anagrams have to be real words?
No. The program only compares letters, so any two strings with the same letter counts are anagrams, such as "abc" and "cab".
Keep learning
Step-by-step lessons:
Python StringsPython SortingPython collections Module
Related:
Python Program to Check Palindrome (String and Number)Python Program to Count Character Frequency in a StringPython sorted() FunctionPython Word Count Program: Count Words in a String
More in string programs:
Python Program to Check Palindrome (String and Number)Python Program to Count Vowels in a StringPython Word Count Program: Count Words in a StringPython Program to Count Character Frequency in a String See all →