sorted() and list.sort()
Python's built-in sorts: sorted() returns a new sorted list from any iterable, and list.sort() sorts a list in place.
In more detail
Both are stable, O(n log n) in the worst case and much faster on partly ordered data. Both accept key= to sort by a computed value and reverse=True for descending order. Use list.sort() when you no longer need the original order and want to save memory.
Related terms
- key function — A function given as key= to sorted, sort, min or max, which turns each item into the value to compare by.
- stable sort — A sort that keeps items with equal keys in the same relative order they had before sorting.
- in-place algorithm — An algorithm that rearranges its input within the input's own memory, using only a constant amount of extra space.
Taught in
- Space, In-Place Work And The Call Stack — Algorithms & Data Structures for Working Engineers