How to Check if a Given String is an Anagram of Another String?

In this tutorial, I will explain how to check if a given string is an anagram of another string in Python. As a Python developer working on natural language processing (NLP) in one of my projects for my USA clients, I came across a situation where I needed to compare text, This led me to explore various methods to check if a given string is an anagram of another string in Python. Let us learn more about this topic today.

What is an Anagram?

An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once. For example: "listen" is an anagram of "silent". "triangle" is an anagram of "integral".

Read How to Check if a String is an Emoji in Python?

Check if a Given String is an Anagram of Another String in Python

Several methods exist in Python to check if a given string is an anagram of another string. We will explore the various approaches:

Method 1: Sort

One of the simplest ways to determine if two strings are anagrams is by sorting the characters in both strings and comparing the sorted versions. If they are identical, the strings are anagrams.

def are_anagrams(str1, str2):
    return sorted(str1) == sorted(str2)

# Example usage:
str1 = "listen"
str2 = "silent"
print(are_anagrams(str1, str2)) 

Output:

True

I have executed the above example code and added the screenshot.

Given String is an Anagram of Another String

In this method, the sorted() function sorts the characters of the strings, and the == operator checks if the sorted lists are equal.

Read How to Check if a String Contains Any Special Character in Python?

Method 2: Use a Counter

Another efficient method is to use the Counter class from Python’s collections module. This method involves counting the frequency of each character in both strings and comparing these counts.

from collections import Counter

def are_anagrams(str1, str2):
    return Counter(str1) == Counter(str2)

# Example usage:
str1 = "listen"
str2 = "silent"
print(are_anagrams(str1, str2)) 

Output:

True

I have executed the above example code and added the screenshot.

Check if a Given String is an Anagram of Another String

The Counter class creates a dictionary-like object where keys are characters and values are their counts in the string. If the two Counter objects are equal, the strings are anagrams.

Read How to Check if String Length is Greater Than 0 in Python?

Method 3: Use a Dictionary

This method involves manually counting the frequency of each character using a dictionary and then comparing the dictionaries.

def are_anagrams(str1, str2):
    if len(str1) != len(str2):
        return False

    count1 = {}
    count2 = {}

    for char in str1:
        count1[char] = count1.get(char, 0) + 1

    for char in str2:
        count2[char] = count2.get(char, 0) + 1

    return count1 == count2

# Example usage:
str1 = "listen"
str2 = "silent"
print(are_anagrams(str1, str2))

Output:

True

I have executed the above example code and added the screenshot.

How to Check if a Given String is an Anagram of Another String

In this method, two dictionaries are created to store the frequency of each character in the strings. The dictionaries are then compared for equality.

Read How to Check if a String is Comma Separated in Python?

Method 4: Optimized Array Count

For a more optimized solution, especially when dealing with only lowercase English letters, you can use an array of fixed size (26 for the alphabet) to count character frequencies.

def are_anagrams(str1, str2):
    if len(str1) != len(str2):
        return False

    count = [0] * 26  # Assuming only lowercase English letters

    for char in str1:
        count[ord(char) - ord('a')] += 1

    for char in str2:
        count[ord(char) - ord('a')] -= 1

    for c in count:
        if c != 0:
            return False

    return True

# Example usage:
str1 = "listen"
str2 = "silent"
print(are_anagrams(str1, str2)) 

Output:

True

Here, ord(char) - ord('a') converts a character to its corresponding index in the array. The counts are incremented for the first string and decremented for the second string. If the array contains only zeros at the end, the strings are anagrams.

Read How to Check if a String is in CamelCase Format Using Python?

Conclusion

In this tutorial, I have explained how to check if a given string is an anagram of another string in Python. I covered some important methods to achieve this task like using sort, counter, dictionary, and optimized array count.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.