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 article, we will discuss different methods to check if two strings are anagram or not.
- How to Reverse a String in Python
- How to Convert Python List to String
- How to Check if a Python String is a Palindrome
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?
Best-suited Python courses for you
Learn Python with these high-rated online courses
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:
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:
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 stringsstr1 = str(input ("Enter string 1: "))str2 = str(input ("Enter string 2: "))
#Convert into lowercase and sortstr1 = sorted(str1.lower())str2 = sorted(str2.lower())
print("String 1 after sorting: ", str1)print("String 2 after sorting: ", str2)
#Define a function to match stringsdef isAnagram(): if (str1 == str2) : return "The strings are anagrams." else: return "The strings are not anagrams."
print(isAnagram())
Output:
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 countersdef 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 stringsstr1 = str(input ("Enter string 1: "))str2 = str(input ("Enter string 2: "))
#Call the functioncheck(str1.lower(), str2.lower())
Output:
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 stringsstr1 = str(input ("Enter string 1: "))str2 = str(input ("Enter string 2: "))
#Declare two empty listsl1=[]l2=[]
##Convert first string into lowercase#append to list 1#and sortfor i in str1: l1.append(i.lower())l1.sort()
##Convert second string into lowercase#append to list 2#and sortfor 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 listsdef isAnagram(): if (l2 == l2) : return "The strings are anagrams." else: return "The strings are not anagrams."
print(isAnagram())
Output
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 anagramsdef 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 stringsstr1 = str(input ("Enter string 1: ")).lower()str2 = str(input ("Enter string 2: ")).lower()
#Function callif isAnagram(str1, str2): print("The strings are anagrams.")else: print("The strings are not anagrams.")
Output:
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.

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