Write a Python Program to Check if Two Strings are Anagrams

Do you know how to check if two strings are anagrams of each other in Python? It’s a common problem and there are multiple ways to solve it.

Two strings are anagrams of each other if they both contain the same characters and each character is present in each string the same number of times. Two ways to check if two strings are anagrams in Python is by using the sorted() function or the collections.Counter() function.

It’s also important to clarify that two words are anagrams if they both have meaning.

Let’s start working with anagrams in Python!

What is an Anagram String in Python?

If two Python strings contain the same characters and each character is present the same number of times (independently of the order) they are anagrams of each other. Both strings must have real meaning to be anagrams. For example, the following strings are anagrams of each other: earth – heart.

Other examples of anagrams are:

'note' and 'tone'
'tea' and 'eat'

So, how can you verify anagrams in Python?

One way to verify anagrams in Python is by using the sorted built-in function.

Let’s see what output the sorted function returns…

>>> sorted('earth')
['a', 'e', 'h', 'r', 't']
>>> sorted('heart')
['a', 'e', 'h', 'r', 't']

The sorted function takes an iterable as an argument and returns a sorted Python list that contains the items in the iterable.

In this specific case, we have passed a string to the sorted function (yes, a string is an iterable) and we get back a list of characters.

Have a look at the output of the sorted function.

How do you think you can use this function to check if two strings are anagrams of each other?

You can simply compare the two lists returned by the sorted function. If the two lists are equal then the two strings are anagrams.

Here is the logic you can use:

>>> sorted('earth') == sorted('heart')
True
>>> sorted('earth') == sorted('hearts')
False

This comparison returns a Python boolean that is True if the two strings are anagrams and False if the two strings are not anagrams.

Python Program to Check if Two Strings are Anagrams Using the sorted Function

Let’s write a simple Python program that reads two strings from the user by calling the input function and checks if the two strings are anagrams.

first_string = input("Provide the first string: ")
second_string = input("Provide the second string: ") 

if sorted(first_string) == sorted(second_string):
    print("The two strings are anagrams of each other.")
else:
    print("The two strings are not anagrams of each other.") 

After reading the two strings from the user input we verify, using a Python if else statement, if the lists returned by the sorted function are the same.

Verify if the program does what it’s expected to do…

$ python anagrams.py
Provide the first string: earth
Provide the second string: heart
The two strings are anagrams of each other.
 
$ python anagrams.py
Provide the first string: earth
Provide the second string: hearts
The two strings are not anagrams of each other. 

Looks good!

You have created a simple program that performs an anagram test between two strings.

Perform Anagram Check in a Python Function

Before making our algorithm to check for anagrams more complex let’s refactor the previous code and move all the logic into a function.

The function takes the two strings as arguments and prints the messages we have seen before.

def anagram_checker(first_value, second_value):
    if sorted(first_value) == sorted(second_value):
        print("The two strings are anagrams of each other.")
    else:
        print("The two strings are not anagrams of each other.")

And here is how you can call the function from the “main” of your Python program.

first_string = input("Provide the first string: ")
second_string = input("Provide the second string: ")
anagram_checker(first_string, second_string) 

Before continuing with this tutorial verify that the new code works as expected.

How to Find Anagrams of a String in a List of Strings

It’s time to learn how to look for anagrams of a string in a list of strings.

Let’s assume you have the following list:

words = ['function', 'heart', 'anagram', 'sort', 'true', 'false']

We want to take one string as user input and find any anagrams for it inside the list of words.

You already know how to get the user input so for now let’s focus on updating the anagram_checker function.

This function will now:

  • Take as arguments the string we are searching anagrams for and the list of words.
  • Return a list that contains any anagrams found.
  • If no anagrams are found the list returned is empty.
def anagram_checker(value, words):
    anagrams = []
    
    for word in words:
        if sorted(word) == sorted(value):
            anagrams.append(word)

    return anagrams

Use a Python for loop to go through each word in the list to verify which one is an anagram for the first value (string) passed to the function.

Let’s test this function to see if it returns the expected results…

words = ['function', 'heart', 'anagram', 'sort', 'true', 'false']

# Test 1
print(anagram_checker('earth', words))

[output]
['heart']

# Test 2
print(anagram_checker('python', words))

[output]
[] 

The two tests executed against this Python code return the correct results.

How Do You Check Anagrams in Python without the sorted Function?

Can you create an anagram program in Python without using the sorted() function?

Yes, you can!

You can create a Python program to check whether two strings are anagrams without using the sorted function. The alternative is to use collections.Counter.

Collections.Counter is a type of dictionary that when applied to a Python string returns a dictionary in which the keys are the characters in the string and the values are the counts of each character (how many times that character appears in the string).

Here is an example of the object returned by collections.Counter:

>>> from collections import Counter
>>> Counter('earth')
Counter({'e': 1, 'a': 1, 'r': 1, 't': 1, 'h': 1})

From the output above you can see that each character in the string ‘earth’ occurs once in the string.

Let’s create a function that takes two strings as inputs and uses collections.Counter to verify if the two strings are anagrams.

from collections import Counter

def anagram_checker(first_string, second_string):
    if Counter(first_string) == Counter(second_string):
        print("The two strings are anagrams of each other.")
    else:
        print("The two strings are not anagrams of each other.")

Provide two values using the input function and then call the anagram_checker() function to verify if they are anagrams or not.

first_string = input("Provide the first string: ")
second_string = input("Provide the second string: ")
anagram_checker(first_string, second_string)

Here is the output of this Python program in both scenarios:

The two strings are anagrams

Provide the first string: earth
Provide the second string: heart
The two strings are anagrams of each other.

The two strings are not anagrams

Provide the first string: earth
Provide the second string: hearts
The two strings are not anagrams of each other.

Now you know another way to check if two given strings are anagrams.

Conclusion

In this tutorial, we went through multiple ways to verify if two strings are anagrams of each other using Python.

We have also seen how to find anagrams of a word in a list of words.

I hope you have found it useful! 🙂

Related article: while going through this tutorial you have used the input() function multiple times. Read the next Codefather tutorial to learn more about the Python input function!

Leave a Comment