sorted() is a Python built-in function that accepts any iterable and returns a new list containing its items in sorted order. Unlike list.sort(), it leaves the original iterable unchanged. section 5.4.2 section 5.4
x = (4, 3, 1, 2) y = sorted(x) y [1, 2, 3, 4] z = sorted(x, reverse=True) z [4, 3, 2, 1]
A tuple becomes a newly returned list; reverse=True changes the order without changing the input. section 5.4.2
Use sorted() when:
- You need to preserve the original list or iterable. section 5.4
- You need descending order with reverse=True. section 5.4.2
- You need a custom ordering with a key function, such as str.lower or a slice-based lambda. section 21.4.2
Default sorting requires comparable item types. Lists of lists are compared element by element, beginning with the first element and continuing to later elements when needed. Mixed numbers and strings raise TypeError. section 5.4
Preserving data while finding a median
For temperatures, use sorted_temps = sorted(temperatures) before selecting or calculating the middle value. This preserves the input order, but a sorted copy uses additional memory; for very large lists, in-place sorting may be preferable when preservation is unnecessary. section 5.9.3
For data larger than available memory, an external utility such as the UNIX sort command may be more practical. Also keep key functions simple because sorting calls them repeatedly. section 21.4.2




