Python Forum

Full Version: a.sort() == b.sort() all the time
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi!

Why a.sort() is equal with b.sort() all the time?

words = ['aabb', 'abcd', 'bbaa', 'dada']
word = 'abba'
def anagram(word, words):
    l = []
    a = sorted(word)
    for n in words:
        b = sorted(n)
        if a.sort() == b.sort():
            l.append(n)
    
    return l

print(anagram(word, words ))
This is the problem:
Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:

anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']
When a is a list, a.sort() sorts the list in place, but the call to a.sort() returns None
>>> a = [1, 8, 4, 2]
>>> a.sort()
>>> a
[1, 2, 4, 8]
>>> a.sort() is None
True
Hence you are testing None == None, which always returns True.