# Python sorting: sorted, sort and the key argument

Published: 2026-11-30

Rights: original
Source: https://kairos-2z6s.onrender.com/res/python-sorting-full-en
`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.

(Test: 3 tests were run, TE-45-A, TE-45-B and TE-45-C. The expected non-zero exit is TE-45-C (exit status 1). Every row has a recorded log in the evidence archive. The evidence table lists the exit status and log hash of every row, and no Exit status line on this page is for the A row.)

### 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:

```bash
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`):

```bash
cat > s.py <<'EOS'
w = ['bb', 'a', 'cc', 'd']
print(sorted(w, key=len))
print(sorted(w, key=len, reverse=True))
EOS
```

Command:

```bash
python3 s.py
```

Recorded 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`):

```bash
cat > s.py <<'EOS'
print(sorted([1, 'a']))
EOS
```

The 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:

```bash
python3 s.py 2>../err.txt; rc=$?; tail -n 1 ../err.txt; exit $rc
```

Recorded 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

- https://docs.python.org/3/howto/sorting.html

## Evidence

- `TE-45-A`: sorted returns a new list and accepts any iterable; list.sort returns None
- `TE-45-B`: key=len sorts by length, equal lengths keep their input order, and reverse=True keeps that order for equal items
- `TE-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.

## Related guides
- [Python: count with a dict or Counter, and meet sets and tuples](https://kairos-2z6s.onrender.com/res/python-counting-sets-tuples-full-en)
- [Python classes: a small example, line by line](https://kairos-2z6s.onrender.com/res/python-class-basics-full-en)
- [Python round: ties go to the even number](https://kairos-2z6s.onrender.com/res/python-round-full-en)
- [Storing API keys in a Python project](https://kairos-2z6s.onrender.com/res/python-store-api-keys-env-vars-en)
- [Python Sets: unique items and set operations](https://kairos-2z6s.onrender.com/res/python-sets-full-en)
- [Python os.environ: read environment variables](https://kairos-2z6s.onrender.com/res/python-os-environ-full-en)
