Sorting arranges elements by their values or by a specified key. Python’s list.sort() changes the list in place; sorted() returns a sorted copy, preserving the original order. section 5.4
Choose the sorting approach to fit the data and task:
- Use reverse=True for reverse order, or key= to compare elements by a chosen value, such as lowercase text. section 5.4 section 21.4.2
- Default sorting requires comparable item types; mixing numbers and strings raises a TypeError. Lists of lists sort by their elements in order. section 5.4
- For large files, weigh memory against convenience: sorted() creates a copy, while an external utility such as UNIX sort can preprocess data larger than memory. section 21.4.2
- Keep key functions simple: they are called repeatedly during sorting, and complex work can slow large sorts. section 21.4.2
Sorting for a median
A temperature list can be sorted in place, then indexed to select a middle value. Alternatively, sort a copy and average the two middle values when the list has an even number of entries. section 5.9.3
x = [2, 4, 1, 3] y = x[:] #1 y.sort() #2 y [1, 2, 3, 4] x [2, 4, 1, 3] #1 A full list slice makes a copy of the list. #2 Sorts method on copy, not original
See how sorting a full-slice copy orders the copy while leaving the original list unchanged. section 5.4
! sort datafile > datafile.srt ! cat datafile.srt AAAAAA CCCCCC QQQQQQ ZZZZZZ
See an external sort utility ordering rows from a data file. section 21.4.2

















