PythonMastery
Python programs · Strings · beginner

Check if two strings are anagrams in Python

Check whether two words or phrases use exactly the same letters, ignoring case and spaces. Uses sorted(), with collections.Counter as a second way.

Two words are anagrams when they use the same letters the same number of times, in a different order: "listen" and "silent". If you sort the letters of both, you get the same result.

The program

python
def is_anagram(first, second):
    first = first.lower().replace(" ", "")
    second = second.lower().replace(" ", "")
    return sorted(first) == sorted(second)


a = input("First word or phrase: ")
b = input("Second word or phrase: ")

if is_anagram(a, b):
    print("They are anagrams.")
else:
    print("They are not anagrams.")

Typed in this example: Dormitory, Dirty room. Press Run to type your own.

output
First word or phrase: Dormitory
Second word or phrase: Dirty room
They are anagrams.

How it works

python
print(sorted("dormitory"))
print(sorted("dirtyroom"))
output
['d', 'i', 'm', 'o', 'o', 'r', 'r', 't', 'y']
['d', 'i', 'm', 'o', 'o', 'r', 'r', 't', 'y']

Another way: Counter

Counter from the collections module counts how many times each letter appears. Two strings are anagrams when their counts are equal:

python
from collections import Counter

print(Counter("listen") == Counter("silent"))
print(Counter("apple") == Counter("paple"))
print(Counter("apple") == Counter("pale"))
output
True
True
False

"pale" has the right letters but only one "p", so it is not an anagram of "apple". For short words both ways are fast. For very long texts, Counter is faster, because it does not need to sort.

Learn the idea: Working with Strings, Functions & Scoping, collections: The Stdlib's Hidden Power