Python sorted() to check if two strings are anagram or not

Given two strings s1 and s2, check if both the strings are anagrams of each other.


Input : s1 = "listen"
        s2 = "silent"
Output : The strings are anagrams.

Input : s1 = "dad"
        s2 = "bad"
Output : The strings aren't anagrams.

Python provides a inbuilt function sorted() which does not modify the original string, but returns sorted string.

Below is the Python implementation of the above approach:





# function to check if two strings are
# anagram or not 
def check(s1, s2):
    # the sorted strings are checked 
    if(sorted(s1)== sorted(s2)):
        print("The strings are anagrams."
        print("The strings aren't anagrams.")         
# driver code  
s1 ="listen"
s2 ="silent" 
check(s1, s2)



The strings are anagrams.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.