Python Sorting with sorted()
Learn Python's sorted() function, key functions, reverse ordering, stable sorting, and when to use list.sort() instead.
Basic
Python's
sorted() function creates a new list containing the items from an iterable in sorted order. It is useful when you want an ordered result without changing the original object.
Get a new sorted list
Pass an iterable to
sorted and Python returns a new list. The input is not changed just because you sorted its values.
Output
Ready to run.
sorted works with any iterable
sorted accepts an iterable, not only a list. The result is always a new list, even when the input is another iterable type.
Output
Ready to run.
Choose a key for the ordering
The keyword-only
key argument receives each item and produces the value Python uses for comparison. The original items are what appear in the resulting list.
Output
Ready to run.
Reverse the ordering
Set
reverse=True to request the opposite sort order. The argument is keyword-only and expects a Boolean value.
Output
Ready to run.
Equal keys keep their original order
sorted is stable: when two items compare equal by their sort key, their relative order from the input is preserved. This makes multi-step sorting possible when each step uses a different key.
Output
Ready to run.
Sort by more than one value
A key function can return a value such as a tuple. Python compares that tuple from left to right, so one key can express primary and secondary ordering rules.
Output
Ready to run.
sorted() and list.sort() do different jobs
The
list.sort() method changes an existing list in place and returns
None. In contrast,
sorted works with any iterable and returns a new list. Choose based on whether you need to preserve the original collection and on whether your input is a list.
Output
Ready to run.
Use the key that matches the question
Sorting is easiest to reason about when the key expresses the information that should determine order. For simple values, the default comparison may be enough; for records or text, a key often makes the intent explicit.
Output
Ready to run.
Keep
sorted as the main tool when you want an ordered copy of an iterable. The Lists lesson remains the owner of list operations; this lesson owns sorting choices,
key and
reverse behavior, stability, and the distinction between
sorted() and
list.sort().
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.