Beginner Python Exercises

Check Anagrams in Python

"listen" and "silent" use the same letters. Normalize both words, sort the letters and compare.

  • Beginner
  • 2 min read
  • 1 runnable example
What you'll learn
  • Normalizing case and spaces
  • Comparing sorted letters
  • Using collections.Counter instead
sorted letters
"listen"
e i l n s t
    "silent"
    e i l n s t
      result
      • equal → anagrams

      Same letters, different order

      The problem

      Word games and puzzles ask whether two words use exactly the same letters: "listen" and "silent", "evil" and "vile". Comparing the words directly fails because the order is different, so you need a form that ignores order.

      Think of it like this

      Checking anagrams is like tipping two bags of letter tiles onto a table and sorting each pile alphabetically. If both sorted piles look identical, the bags held the same letters, whatever word they spelled before.

      From letter tiles to code
      character.isalpha()🧹 Remove spaces and punctuation
      character.lower()🔡 Make all tiles the same case
      sorted(...)🔤 Sort each pile alphabetically
      normalize(first) == normalize(second)⚖️ Are the piles identical?
      Same letters in sorted order means the words are anagrams.
      In one sentence

      Two words or phrases are anagrams when they contain exactly the same letters the same number of times, in any order.

      Key points

      1. normalize keeps only letters with character.isalpha() and makes them lowercase.
      2. sorted(...) puts the letters in alphabetical order, so "listen" and "silent" both become the same list.
      3. normalize(first) == normalize(second) compares the two sorted lists.
      4. result holds "are" or "are not" for the final sentence.

      When should you use it?

      • Word games and puzzles.
      • Grouping words that use the same letters.
      • Learning to compare things by a normalized form instead of directly.

      When not to use it

      • Very long texts: counting letters with Counter avoids sorting and is faster.
      • Words with accented letters if accents should not matter: remove the accents first.

      Example code

      Run code →
      main.py
      def normalize(text):
          # Ignore spaces, punctuation, and letter case.
          return sorted(character.lower() for character in text if character.isalpha())
      
      first, second = "listen", "silent"
      result = "are" if normalize(first) == normalize(second) else "are not"
      print(f"{first} and {second} {result} anagrams")
      Get a Run button for this example

      Result of running the code

      listen and silent are anagrams

      Code explanation

      normalize goes through the text, keeps only letters, makes them lowercase and returns them as a sorted list. Calling it on "listen" and on "silent" gives the same list, because both words contain the same letters. The comparison is therefore True and result becomes "are".

      Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

      Practice exercises

      Modify the runnable example with the exercises below to build understanding beyond copying the result.

      1. Change the input and predict the output before running.
      2. Handle empty or invalid input.
      3. Wrap the logic in a function and add more test cases.
      Run in the Python compiler →

      Common mistakes

      Comparing sets of letters

      Sets ignore how often a letter appears, so "aab" and "abb" would match.

      Problem
      set(first) == set(second)
      Fix
      sorted(first) == sorted(second)

      Finished this lesson?

      Mark it as learned to track your progress.

      Practice with a challenge

      Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

      All challenges