Home >Backend Development >Python Tutorial >Why Doesn't Python's `list.sort()` Return the Sorted List?
Understanding Return Values of List Sorting
In Python, utilizing the "sort()" function on lists does not directly return the sorted list. Instead, it modifies the original list in-place without producing an explicit return value.
This deviation from expectation can lead to confusion, as the caller might anticipate the function to return the sorted list. To clarify, "list.sort()" doesn't create a new sorted list but rather reorganizes the elements within the existing list.
To obtain the desired sorted list as the output, the code should explicitly return the sorted list. The corrected version of the provided code snippet should be:
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) newList.sort() return newList
By adding "newList.sort()" outside the loop, the list is sorted in place. Then, returning "newList" ensures that the sorted list is available to the caller.
The above is the detailed content of Why Doesn't Python's `list.sort()` Return the Sorted List?. For more information, please follow other related articles on the PHP Chinese website!