0
0
PythonProgramBeginner · 2 min read

Python Program to Check Anagram with Examples and Explanation

You can check if two strings are anagrams in Python by comparing their sorted characters using sorted(str1) == sorted(str2).
📋

Examples

Input"listen", "silent"
OutputTrue
Input"hello", "world"
OutputFalse
Input"aabbcc", "abcabc"
OutputTrue
🧠

How to Think About It

To check if two words are anagrams, think about whether they have the exact same letters in the same amounts. If you sort both words alphabetically, they should look identical if they are anagrams. So, compare the sorted versions of both words to decide.
📐

Algorithm

1
Get two input strings.
2
Convert both strings to lowercase to ignore case differences.
3
Sort the characters of both strings.
4
Compare the sorted strings.
5
Return True if they are the same, otherwise False.
💻

Code

python
def are_anagrams(str1, str2):
    return sorted(str1.lower()) == sorted(str2.lower())

print(are_anagrams('listen', 'silent'))  # True
print(are_anagrams('hello', 'world'))    # False
Output
True False
🔍

Dry Run

Let's trace the example 'listen' and 'silent' through the code

1

Input strings

str1 = 'listen', str2 = 'silent'

2

Convert to lowercase

str1.lower() = 'listen', str2.lower() = 'silent'

3

Sort characters

sorted('listen') = ['e', 'i', 'l', 'n', 's', 't'], sorted('silent') = ['e', 'i', 'l', 'n', 's', 't']

4

Compare sorted lists

['e', 'i', 'l', 'n', 's', 't'] == ['e', 'i', 'l', 'n', 's', 't'] -> True

StepSorted str1Sorted str2Are Equal?
1['e', 'i', 'l', 'n', 's', 't']['e', 'i', 'l', 'n', 's', 't']True
💡

Why This Works

Step 1: Lowercase conversion

Using lower() makes the comparison case-insensitive, so 'Listen' and 'silent' match.

Step 2: Sorting characters

Sorting rearranges letters alphabetically, so anagrams become identical sequences.

Step 3: Comparing sorted lists

If sorted lists are equal, the original strings have the same letters in the same counts, confirming an anagram.

🔄

Alternative Approaches

Using character count with collections.Counter
python
from collections import Counter

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

print(are_anagrams('listen', 'silent'))  # True
print(are_anagrams('hello', 'world'))    # False
This method counts each letter's frequency and compares counts, which can be faster for long strings.
Manual counting with dictionary
python
def are_anagrams(str1, str2):
    str1, str2 = str1.lower(), str2.lower()
    count = {}
    for ch in str1:
        count[ch] = count.get(ch, 0) + 1
    for ch in str2:
        if ch not in count or count[ch] == 0:
            return False
        count[ch] -= 1
    return all(v == 0 for v in count.values())

print(are_anagrams('listen', 'silent'))  # True
print(are_anagrams('hello', 'world'))    # False
This approach manually tracks letter counts without extra imports but is more code.

Complexity: O(n log n) time, O(n) space

Time Complexity

Sorting both strings takes O(n log n) time where n is the length of the strings, which dominates the runtime.

Space Complexity

Sorting creates new lists of characters, so extra space proportional to the string length is used.

Which Approach is Fastest?

Using collections.Counter runs in O(n) time and is faster for long strings, but sorting is simpler and often sufficient.

ApproachTimeSpaceBest For
Sorting and comparingO(n log n)O(n)Simple and short strings
collections.CounterO(n)O(n)Long strings with many characters
Manual countingO(n)O(n)When avoiding imports or for learning purposes
💡
Always convert strings to lowercase before checking anagrams to ignore case differences.
⚠️
Forgetting to normalize case or ignoring spaces and punctuation can cause wrong anagram results.