Home / Python / Example programs / Strings

Python program: Check whether two words are anagrams

Anagrams use exactly the same letters: "listen" and "silent".

The code

from collections import Counter

def are_anagrams(a, b):
    clean = lambda s: s.replace(" ", "").lower()
    return sorted(clean(a)) == sorted(clean(b))

print(are_anagrams("listen", "silent"))
print(are_anagrams("Dormitory", "Dirty room"))
print(are_anagrams("hello", "world"))
print(Counter("listen") == Counter("silent"))   # another way

Output

True
True
False
True

How it works

Sorting both words puts the letters in the same order if they are anagrams. Comparing letter counts with Counter works too.

Python features used

Learn the ideas behind it in the free lesson Strings.