Python sorting: sorted, sort and the key argument
sorted(iterable) returns a new sorted list; list.sort() sorts in place and returns None; key chooses the sort value.
Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.
TE-45-A: sorted returns a new list and accepts any iterable; list.sort returns None
No setup needed: the command below creates what it uses in the throwaway folder.
Command:
python3 -c "l=[3,1,2]; print(sorted(l), l); print(l.sort(), l); print(sorted('ba'), sorted({'b':1,'a':2}))"Recorded output:
[1, 2, 3] [3, 1, 2]
None [1, 2, 3]
['a', 'b'] ['a', 'b']TE-45-B: key=len sorts by length, equal lengths keep their input order, and reverse=True keeps that order for equal items
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
w = ['bb', 'a', 'cc', 'd']
print(sorted(w, key=len))
print(sorted(w, key=len, reverse=True))
EOSCommand:
python3 s.pyRecorded output:
['a', 'd', 'bb', 'cc']
['bb', 'cc', 'a', 'd']Exit status: 0. The output matches the expected text written before the run.
TE-45-C: expected non-zero exit: sorted raises TypeError when the items cannot be compared with each other
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
print(sorted([1, 'a']))
EOSThe file ../err.txt sits one level above the working folder, inside the same throwaway tree. The output block below shows only the last line of the error; the full traceback went to ../err.txt.
Command:
python3 s.py 2>../err.txt; rc=$?; tail -n 1 ../err.txt; exit $rcRecorded output:
TypeError: '<' not supported between instances of 'str' and 'int'Exit status: 1. This status and the output match what was written before the run.
Reading the recorded output
The first line shows two values. sorted(l) returned [1, 2, 3], and l itself was still [3, 1, 2] afterwards, so sorted made a new list. In the second line, l.sort() printed None, because the method returns nothing, and l then printed [1, 2, 3], so the sort changed the original list. In the third line, sorted('ba') gave ['a', 'b'], a list of single characters. sorted on the dict {'b': 1, 'a': 2} also gave ['a', 'b'], the keys in order.
TE-45-B: with key=len, the list ['bb', 'a', 'cc', 'd'] came out as ['a', 'd', 'bb', 'cc'], and a stays before d and bb before cc, as in the input. With reverse=True the result was ['bb', 'cc', 'a', 'd']: longest first, and equal lengths still in input order. TE-45-C: sorting [1, 'a'] stopped with TypeError: '<' not supported between instances of 'str' and 'int', and exit status 1.
Limits
Covers lists, strings and dict keys, one key function (len), reverse=True and the order of equal items in one example. Sorting by several keys is outside this page.
Source
Evidence
TE-45-A: sorted returns a new list and accepts any iterable; list.sort returns NoneTE-45-B: key=len sorts by length, equal lengths keep their input order, and reverse=True keeps that order for equal itemsTE-45-C: expected non-zero exit: sorted raises TypeError when the items cannot be compared with each other
- logs: one recorded log for each row above
- Recorded on: Linux x86_64, kernel 7.3.4; bash 5.1.16; git 2.34.1; python 3.10.12; findutils 4.8.0; grep 3.7; sed 4.8; gawk 5.1.0; tar 1.34; curl 7.81.0. Locale C.UTF-8, TZ=UTC.
Evidence table
| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-45-A | sorted returns a new list and accepts any iterable; list.sort returns None | 0 | PASS | 9d4c626fece4 | | TE-45-B | key=len sorts by length, equal lengths keep their input order, and reverse=True keeps that order for equal items | 0 | PASS | 679b75647474 | | TE-45-C | expected non-zero exit: sorted raises TypeError when the items cannot be compared with each other | 1 | PASS | fc8fd3da5216 |
Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.
All full guides: All guides