Why does "return list.sort()" return None, not the list?

185

I've been able to verify that the findUniqueWords does result in a sorted list. However, it does not return the list. Why?

def findUniqueWords(theList):
    newList = []
    words = []

    # Read a line at a time
    for item in theList:

        # Remove any punctuation from the line
        cleaned = cleanUp(item)

        # Split the line into separate words
        words = cleaned.split()

        # Evaluate each word
        for word in words:

            # Count each unique word
            if word not in newList:
                newList.append(word)

    answer = newList.sort()
    return answer

This question is tagged with python list sorting return

~ Asked on 2011-09-04 17:58:28

The Best Answer is


226

list.sort sorts the list in place, i.e. it doesn't return a new list. Just write

newList.sort()
return newList

~ Answered on 2011-09-04 18:00:31


156

The problem is here:

answer = newList.sort()

sort does not return the sorted list; rather, it sorts the list in place.

Use:

answer = sorted(newList)

~ Answered on 2011-09-04 18:00:51


Most Viewed Questions: