Introduction to Anagrams in Python

Featured Img Anagram

Hey there! Today we are going to learn about implementing an interesting topic known as Anagrams in Python. Let us first understand what an Anagram is.

What is an Anagram?

Anagram is interesting suspense behind the words and sentences. If all the letters of a particular word or sentence can form other words or sentences after rearranging them, then all of them are anagrams to each other.

Some examples of anagrams are ‘sram’ and ‘mars’, ‘top’ and ‘otp’, and many more. But now the next question is why to even learn about anagrams?

Anagrams can be really helpful to writers as they add an extra layer of suspense to the writing and they are a clever and playful way to make the writing interesting. Using anagrams can be really interesting and fun.

Checking for Anagrams in Python

Let’s look at how we can identify anagrams in Python using a simple algorithm.

Algorithm for checking if two words are Anagrams or not

The steps below show how to check if two strings are anagrams or not.

STEP 1: Take input of the 1st string
STEP 2: Take input of the 2nd string
STEP 3: Sort all the letters of both the strings
STEP 4: Check if after sorting both the strings match.
if they match: Anagram
if not: Not an Anagram

Program to check if two strings are Anagrams or not

s1 = input()
s2 = input()
s1 = sorted(s1)
s2 = sorted(s2)
    print("Not an Anagram")

The results for some sample strings are shown below. The first strings which were checked were tac and cat, and tic and cat. We can clearly see that the first pair is an anagram whereas the second pair is not an anagram.

Not an Anagram


Congratulations! We learned about Anagrams and how to implement them in the Python programming language. I hope now you are clear with anagrams and can implement it yourself!

Happy coding! Thank you for reading!