Ad space (banner)
🐍Python Lessons
Lesson 65 / 69

Checking Whether Two Words Are Anagrams

This lesson covers how to check whether two words are anagrams (words that can be rearranged into each other), so you can learn a practical string-comparison technique. It's written for anyone who searched "Python anagram check" and landed here.

An anagram is a word formed by rearranging the letters of another word (for example, "listen" and "silent"). You can check this by rearranging the letters of both strings and comparing whether they match. This relies on the fact that if the types and counts of letters match exactly, the words are anagrams of each other, regardless of the original order.

The sample code unifies case with sorted(a.lower()) and sorted(b.lower()), sorting the letters of each string before comparing the results. Applied to a string, sorted() returns a sorted list of individual characters.

A common beginner mistake is forgetting to unify the case first (with something like .lower()) if you want a case-insensitive comparison. Without normalizing first, words that should be recognized as anagrams can be judged as different strings.

For longer strings, counting how many times each character appears with a dictionary is a faster way to check. It looks like a simple word game, but it's a useful exercise in practical string comparison.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)