Hone

Lessons · Python · sort() vs sorted()

Sorting in place versus sorting a copy

list.sort() sorts the list itself and returns None; sorted(x) leaves x alone and returns a new sorted list.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

x = x.sort() is a classic that leaves you with None. And sorting the caller's list in place can quietly break their code.

How to think about it

Ask: do I own this list, and do I want it changed? Yes: .sort(). Otherwise, or when the input is not a list (a tuple, a dict's keys): sorted().

Worked example

scores = [3, 1, 2]
Unsorted input.
ordered = sorted(scores)
New list [1, 2, 3]; scores is still [3, 1, 2].
scores.sort()
Now scores itself is [1, 2, 3]. Returns None.
print(sorted({"b": 1, "a": 2}))
["a", "b"]: sorted() works on anything iterable.

Your turn

Get a sorted copy without changing the original.

ranked = (scores, reverse=True)

The trap

result = items.sort() then using result. It is None. Either use items afterwards, or use sorted().

Next in Python

Every Python lesson on one page

Practise sort() vs sorted() on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.