Skip to content
Devtoolry

Strings · beginner

Python Program to Check if Two Strings are Anagrams

Check whether two strings are anagrams in Python by sorting their letters or counting them with collections.Counter, ignoring case and spaces.

Two words are anagrams when they use exactly the same letters the same number of times: "listen" and "silent", or "Dormitory" and "dirty room". Sorting the letters of both gives the same sequence when they are anagrams.

Anagram checks appear in word games, puzzle solvers and coding interviews. The sorting method is the easiest to explain; counting letters is faster for long texts. Both ignore case and spaces here, because "Dormitory" and "dirty room" should count as a match.

The program

Python
def normalize(text):
    return sorted(text.lower().replace(" ", ""))

def is_anagram(a, b):
    return normalize(a) == normalize(b)

print(is_anagram("listen", "silent"))
print(is_anagram("Dormitory", "dirty room"))
print(is_anagram("hello", "world"))
Output
True
True
False

How it works

  1. lower() makes the check case-insensitive and replace(" ", "") removes spaces.
  2. sorted() returns the letters as a sorted list: "listen" and "silent" both become ['e', 'i', 'l', 'n', 's', 't'].
  3. Two lists are equal when they have the same items in the same order, so equal sorted lists mean the words are anagrams.

Watch it run line by line

Visualize the second call and watch normalize return the same sorted list for "Dormitory" and "dirty room" in two separate frames.

“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.

Another way: Counting letters with Counter

Counter counts each letter. Comparing two Counters checks that every letter appears equally often. It avoids sorting, which matters for very long strings.

Python
from collections import Counter

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

print(is_anagram("Astronomer", "Moon starer"))
print(Counter("banana"))
Output
True
Counter({'a': 3, 'n': 2, 'b': 1})

Common mistakes

  • Comparing set(a) == set(b): sets ignore how often a letter appears, so "aab" and "abb" look like anagrams.
  • Forgetting to remove spaces or punctuation when comparing phrases.
  • Checking only that the lengths are equal, which is necessary but not enough.
  • Calling a.sort() on a string: strings have no sort method. sorted(a) works on any iterable and returns a list.

Try it yourself

  • Group a list of words into anagram groups, using the sorted letters as a dictionary key.
  • Ignore punctuation too, using ch.isalpha().

Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 Python examples, or write your own program in the online Python Compiler.