How to Check if Two Python Strings are Anagrams

How to Check if Two Python Strings are Anagrams

4 mins read6.7K Views Comment
Anshuman
Anshuman Singh
Senior Executive - Content
Updated on Apr 15, 2025 09:38 IST

An Anagram is a word or phrase that is formed by rearranging all the letters of a different word or phrase exactly once such as elbow and below. In this article, we will discuss different methods to check if two strings are anagram or not.

How to Check if Two Python Strings are Anagrams

Python strings are amongst the most frequently asked questions for beginners in Python programming. Whether you’re polishing your coding skills or preparing for interviews, there are a few common programs you will definitely come across, for example:

If you want to get hands-on experience, pursue Python Courses & Certifications available online. And if you are short on funds, you can opt for Free Pyhton Courses & Certifications Online!

In this article, we will focus on another such program – how to determine if two strings are anagrams or not using various methods.

Table of Content

But first, for the unaware, let’s talk about what an anagram is, shall we?

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
3 hours
Free
19 hours
– / –
16 weeks
Free
2 hours
– / –
– / –
4.24 K
2 weeks
3 K
3 weeks
– / –
40 hours

What is an Anagram?

An Anagram is a word or phrase that is formed by rearranging all the letters of a different word or phrase exactly once. For instance:

2022_07_image-117.jpg

All these are examples of anagrams. Each word or phrase has the exact same letters as the other, only arranged differently. Interesting, right?

In Python, two strings can be anagrams if all characters of one string can be rearranged into a sequence resulting in another string. Below, we have discussed different ways in which we can check the same:

What are Perfect Squares?
What are Perfect Squares?
In this article, we will discuss perfect squares, and different methods to check the perfect square and finally, we will use python to determine the number of perfect squares in...read more
What is a Prime Number?
What is a Prime Number?
In this article we have covered the concept of Prime Number in Mathematics. Learn what is a prime number, what are the different prime numbers between 1-100 and 101-1000, and...read more
How to Find the Factorial of a Number Using Python
How to Find the Factorial of a Number Using Python
In this article, we will discuss different methods to find the factorial of a number in python using for, while, ternary operator and math module. While practicing Python programming as...read more

Methods to Check if Two Strings are Anagrams

Method 1 – Sort both strings and compare

This method first converts both input strings to lowercase and then sorts the strings using the sort() method. The resulting strings are then compared and if they match, they are anagrams. It’s as simple as it sounds!


 
#Enter input strings
str1 = str(input ("Enter string 1: "))
str2 = str(input ("Enter string 2: "))
#Convert into lowercase and sort
str1 = sorted(str1.lower())
str2 = sorted(str2.lower())
print("String 1 after sorting: ", str1)
print("String 2 after sorting: ", str2)
#Define a function to match strings
def isAnagram():
if (str1 == str2) :
return "The strings are anagrams."
else:
return "The strings are not anagrams."
print(isAnagram())
Copy code

Output:

2022_07_image-118.jpg

Method 2 – Using the counter() method

For this method too, we first convert the strings to lowercase. Then we import the counter from the collections library in Python. We will apply this method to both strings and compare the counters for both strings. If the counters match, the strings are anagrams.


 
from collections import Counter
#Define a function to match counters
def check(str1,str2):
print(Counter(str1))
print(Counter(str2))
if (Counter(str1) == Counter(str2)) :
return "The strings are anagrams."
else:
return "The strings are not anagrams."
#Enter input strings
str1 = str(input ("Enter string 1: "))
str2 = str(input ("Enter string 2: "))
#Call the function
check(str1.lower(), str2.lower())
Copy code

Output:

2022_07_image-119.jpg
Bitwise Operators in Python
Bitwise Operators in Python
In this article, we will focus on focus on bitwise operators and understand how they perform computations in Python through examples.
Keywords in Python
Keywords in Python
Python has set of keywords that are reserved words, that can’t be used for variable name, function name, or any other identifiers. In this article, we will briefly discuss all...read more
Python Split() Function for Strings
Python Split() Function for Strings
The Python split() function divides a string into a list of substrings based on a specified delimiter. By default, it splits by any whitespace and returns a list of words....read more

Method 3 – Using lists and append() method

Another method is to declare two empty lists l1 and l2. Both input strings are converted to lowercase and appended to l1 and l2 respectively. The lists are then sorted and compared. If matched, the strings are anagrams.


 
#Enter input strings
str1 = str(input ("Enter string 1: "))
str2 = str(input ("Enter string 2: "))
#Declare two empty lists
l1=[]
l2=[]
##Convert first string into lowercase
#append to list 1
#and sort
for i in str1:
l1.append(i.lower())
l1.sort()
##Convert second string into lowercase
#append to list 2
#and sort
for j in str2:
l2.append(j.lower())
l2.sort()
print("List 1 after sorting: ", l1)
print("List 2 after sorting: ", l2)
#Define a function to match lists
def isAnagram():
if (l2 == l2) :
return "The strings are anagrams."
else:
return "The strings are not anagrams."
print(isAnagram())
Copy code

Output

2022_07_image-120.jpg

Method 4 – Using count arrays

We are already aware that 1-byte (8-bits) character sets can contain 256 characters. So, in this method, we perform the following steps:

  • Create count arrays of size 256 to store the input strings.
  • Initialize the count arrays to 0.
  • Iterate through all characters of the strings.
  • After each iteration, the character count is incremented by one in the corresponding count array.
  • Compare the count arrays. If they match, the strings are anagrams.

 
total_char = 256
#Define a function to check if strings are anagrams
def isAnagram(str1, str2):
#Create two count arrays and initialize all values as 0
count1 = [0] * total_char
count2 = [0] * total_char
#For each character in input strings,
#increment count corresponding to count array
for i in str1:
count1[ord(i)] += 1
for i in str2:
count2[ord(i)] += 1
#Check if strings are of the same length
if len(str1) != len(str2):
return 0
#Compare count arrays
for i in range(total_char):
if count1[i] != count2[i]:
return 0
return 1
#Enter input strings
str1 = str(input ("Enter string 1: ")).lower()
str2 = str(input ("Enter string 2: ")).lower()
#Function call
if isAnagram(str1, str2):
print("The strings are anagrams.")
else:
print("The strings are not anagrams.")
Copy code

Output:

2022_07_image-121.jpg
How to Check if Two Python Strings are Anagrams
How to Check if Two Python Strings are Anagrams
An Anagram is a word or phrase that is formed by rearranging all the letters of a different word or phrase exactly once such as elbow and below. In this...read more
How to Convert Celsius to Fahrenheit in Python
How to Convert Celsius to Fahrenheit in Python
One of the most common Python programs for beginners is to convert temperature from Celsius to Fahrenheit and vice versa. This tutorial will help you learn how to perform both...read more
Difference Between List and Tuple in Python
Difference Between List and Tuple in Python
Confused with what list and tuples in Python. Don’t worry the article will clear all your doubts. List and Tuple in Python are the data structures that store and manipulate...read more

Conclusion

Hope this article will be helpful for you to understand the different ways in which one can check if two Python strings are anagrams or not. If you wish to learn more about Python and practice Python programming, you can explore related articles here.

FAQs Related to How to Check if Two Python Strings are Anagrams

What is an anagram?

An anagram is a word or phrase formed by rearranging the letters of another word or phrase. To qualify as an anagram, both words must use the exact same letters, just in a different order. For example, listen and silent are anagrams because they contain the same letters and the same number of each letter.

Why should I convert strings to lowercase before checking for anagrams?

Python treats uppercase and lowercase letters as different characters. This means A and a are not the same. To avoid incorrect comparisons, converting both strings to lowercase is important before checking for anagrams.

How can I check if two strings are anagrams in a simple way?

One simple way to check for anagrams is to sort both strings and compare them. If the sorted versions of the two strings are the same, then they are anagrams. This method works well because sorting puts all letters in the same order, making comparison easy and reliable.

Is there a way to compare letters without sorting?

Yes, there is. You can compare the number of times each letter appears in the two strings. If both strings have the same count for each letter, they are anagrams. 

Python has built-in tools to help count letters, which makes this method worthwhile when performance is essential.

What errors should I avoid while checking for anagrams?

Before checking for anagrams, you should:

  • Clean the input strings.
  • Remove spaces
  • Ignore punctuation, and
  • Ensure both strings are the same length.

Any mismatch in length or extra characters can lead to incorrect results. Proper input cleaning ensures accurate comparison.

About the Author
author-image
Anshuman Singh
Senior Executive - Content

Anshuman Singh is an accomplished content writer with over three years of experience specializing in cybersecurity, cloud computing, networking, and software testing. Known for his clear, concise, and informative wr... Read Full Bio