Sorting in Place or Producing a Sorted Copy
Changing a list in place exposes the order to existing references. A sorted result returned as a separate list can preserve source order.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace shared references
When a list holds 3, 1, 2 and a second name shares it, Python's list sort changes the order seen by both names. The method supplies None as its return value. Return values and effects can explain an assignment that accidentally loses its list binding.
Reuse the source when needed
If a report requires both receipt order and sorted order, obtain a sorted result separately. The returned list can still share referenced elements. See shallow copying for why this matters when rows are mutable.[1]
Inspect the caller's reference after sorting
Start with readings = [7, 1, 5] and let arrival_order refer to the same list. Calling readings.sort() changes the referenced list to [1, 5, 7] and returns None. Using sorted(readings) instead creates a new list that can be stored as a separate view while preserving arrival order. Check both objects after the operation. A shallow sorted result still refers to the original element objects. See mutable values.
Budget the new list when inputs are large
Creating a second list of a million existing record references retains both outer lists, even if no record itself is copied. In-place sorting gives up access to the original order through aliases, and sorting implementations can still allocate temporary storage. If the displayed order is needed only once, keep the sorted copy local to that use. A regression test can compare the arrival sequence after producing the sorted view. See function input ownership.