Home > Backend Development > Python Tutorial > Why Doesn't Python's `list.sort()` Return the Sorted List?

Why Doesn't Python's `list.sort()` Return the Sorted List?

Mary-Kate Olsen
Release: 2024-12-10 11:37:11
Original
847 people have browsed it

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template