The specific issue
x.sort()
works in-place if x
is a list. This means the sort method changes the objects internal representation. It also returns None
which is the reason why it doesn't work as intended.
If x
is a string, there is no .sort()
method as strings are immutable.
I recommend to use the sorted()
function instead, which returns the sorted string.
The more general issues
There are two more general issues:
- Runtime: This is an O(log(n) * n) solution
- Unicode modifiers and compound glyphs
- Print: You print the value, but instead you should return the result. How would you test your code?
Unicode modifiers
Lets say you wrote the function more compact:
def is_anagram(a: str, b: str) -> bool:
return sorted(a) == sorted(b)
This works fine for normal characters, but fails for compound glyphs. For example, the thumbsup / thumbsdown emoji can be modified to have different colors. The change in color is actually a second unicode "character" which gives the skin tone. The modifier and the previous character belong together, but sorted
just looks at the code points. Which results in this:
>>> is_anagram("", "")
True # <-- This should be False!
Sublime Text shows the actual code points:

You can easily fix this by using the grapheme package:
from grapheme import graphemes
def is_anagram(a: str, b: str) -> bool:
return sorted(graphemes(a)) == sorted(graphemes(b))
Runtime
You can get O(n) runtime if you don't sort, but instead count characters:
from collections import Counter
from grapheme import grahemes
def is_anagram(a: str, b: str) -> bool:
return not (Counter(grapheme(a)) - Counter(grapheme(b)))