Why Python’s list.sort() Returns None and What It Means for Your Code
The article explains why Python’s list.sort() method returns None instead of a sorted list, covering the command‑query separation principle, readability considerations from Guido van Rossum, and performance reasons that favor in‑place sorting to avoid unnecessary copies.
For beginners learning Python, a common pitfall is expecting list.sort() to return the sorted list. Consider the following method definition:
methods = ['blogger.deletePost', 'blogger.getUsersBlogs', 'metaWeblog.editPost', 'metaWeblog.getCategories', 'metaWeblog.getPost', 'metaWeblog.getRecentPosts', 'metaWeblog.newMediaObject', 'metaWeblog.newPost', 'wp.newCategory']When we try to return the result with return methods.sort(), the output is None. This is because list.sort() sorts the list in place and does not produce a return value.
From a design perspective, this follows the Command‑Query Separation principle, which states that a method should either perform an action (command) or return data (query), but not both. Since list.sort() mutates the list, it is a command and therefore should not return a value.
Guido van Rossum also explained on the Python‑Dev mailing list that the return value was deliberately set to None to reinforce this distinction.
In situations where performance matters, making a copy of the list just to sort it would be wasteful. Therefore, list.sort() sorts the list in place. To remind you of that fact, it does not return the sorted list, preventing accidental overwriting when you need both sorted and unsorted versions.
Consequently, when you use sort(), you must keep a separate reference to the original list if you need it later, as the original ordering is lost after sorting.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
