PythonPython ListsSort versus sorted
What is the difference between `sort()` and `sorted()`?
Question 86 of 88 · Updated
On this page
list.sort() reorders an existing list and returns None. sorted(iterable) returns a new sorted list without reordering the input list. Choose based on whether you need to preserve the original order.
Quick comparison#
| Feature | sort() | sorted() |
|---|---|---|
| Type | List method | Built-in function |
| Input | List | Any iterable with sortable elements |
| Changes original list | Yes | No |
| Returns | None | New list |
| Options | key, reverse | key, reverse |
Practical example: Preserve the original order#
Imagine keeping the order in which customer ratings arrived while displaying a sorted version.
PYTHONratings = [3, 1, 2] ordered = sorted(ratings) print(ordered) # [1, 2, 3] print(ratings) # [3, 1, 2] ratings.sort() print(ratings) # [1, 2, 3]
Use sorted() when both versions are needed. Use sort() when the original order no longer matters.
Sorting other iterables#
Unlike the list method, sorted() also accepts tuples, strings and generators.
| Expression | Result |
|---|---|
sorted((3, 1, 2)) | [1, 2, 3] |
sorted('cab') | ['a', 'b', 'c'] |
sorted([3, 1, 2], reverse=True) | [3, 2, 1] |
Both sorting operations support custom keys and preserve the relative order of equal keys. Note that sorted() consumes an iterator and does not deep-copy its elements.
Common mistake#
Avoid assigning ratings = ratings.sort(), because the method returns None. Instead, call ratings.sort() by itself or use ratings = sorted(ratings) to bind the name to a new list.
Takeaway: Use sort() to update a list in place; use sorted() for a separate sorted result or for input that is not a list.
Official references#
References
- 1.Python Sorting HOW TOdocs.python.org
- 2.Built-in sorted()docs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design