How to Check if Two Words are Anagrams in Python?

Estimated read time 2 min read

To check if two words are anagrams in Python, you can compare if their sorted versions are equal. Anagrams are words that have the same characters but in a different order. By sorting both words and comparing them, you can determine if they contain the same characters.

Here’s an example code snippet that demonstrates how to check if two words are anagrams:

def are_anagrams(word1, word2):
    # Convert words to lowercase to ignore case sensitivity
    word1 = word1.lower()
    word2 = word2.lower()
    # Sort the characters of each word
    sorted_word1 = sorted(word1)
    sorted_word2 = sorted(word2)
    # Check if the sorted words are equal
    if sorted_word1 == sorted_word2:
        return True
        return False

# Example usage
word1 = "listen"
word2 = "silent"
if are_anagrams(word1, word2):
    print(f"{word1} and {word2} are anagrams.")
    print(f"{word1} and {word2} are not anagrams.")

In this example, the are_anagrams function takes two words (word1 and word2) as input. The words are converted to lowercase using the lower() method to ignore case sensitivity. Then, the characters of each word are sorted using the sorted() function.

The sorted versions of word1 and word2 are compared using the equality operator (==). If the sorted words are equal, it means the words contain the same characters and are anagrams. The function returns True in this case. Otherwise, it returns False.

Finally, we call the are_anagrams function with example words “listen” and “silent”. If the words are anagrams, it prints “{word1} and {word2} are anagrams.” Otherwise, it prints “{word1} and {word2} are not anagrams.”

Note that this approach is case-insensitive. If you want the anagram check to be case-sensitive, you can omit the lower() conversion.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply