← Back

Home › Output practice › sort() vs sorted()

Predict the output: sort() vs sorted()

🔮 Predict the outputTopic: listsDifficulty: mediumNo login needed

The snippet

The question is not really about sorting. It checks whether you remember that sorted() returns a new list at that moment — later mutations of that new list are never re-sorted for you.

scores = [7, 3, 9]
ranking = sorted(scores)
ranking.append(5)
print(scores)
print(ranking)

Your prediction

Type exactly what this program prints — one line per print() call:

The output

[7, 3, 9]
[3, 7, 9, 5]

Verified against CPython 3.11 in this repo's build

Line-by-line explanation

  1. scores = [7, 3, 9]
    The original stays as authored: sorted does not touch it.
  2. ranking = sorted(scores)
    A new list [3, 7, 9] is built. From here scores and ranking are unrelated objects.
  3. ranking.append(5)
    Appending inserts at the end — it does not ask "where does 5 belong". Nothing re-sorts after the fact.
  4. print(scores)
    [7, 3, 9] — unmutated, because sorted() copied first.
  5. print(ranking)
    [3, 7, 9, 5]. Sorted *was* true when it was created; it is not a promise about the future.

The rule you can reuse

sorted(x) returns a new list; x.sort() mutates and returns None. Sort again after mutating, or keep the collection in a heapq heap if you need the order maintained.

Why most predictions break here

Answering [3, 5, 7, 9]. The 5 goes to the end — append knows nothing about order. Also do not write ranking = scores.sort(): that assigns None and, worse, mutates scores.

Quick fire

Same rule, two more shapes. Predict first, then open.

Predict this too
print(sorted([10, 9, 2]))
print(sorted(["beta", "Alpha", "gamma"]))

Output
[2, 9, 10]
['Alpha', 'beta', 'gamma']

Numbers sort numerically; strings sort by code point, and every uppercase letter is *before* lowercase → ['Alpha', 'beta', 'gamma'].

Predict this too
print(sorted(["a", "bb", "c"], key=len))
print(sorted(["a", "bb", "c"]))

Output
['a', 'c', 'bb']
['a', 'bb', 'c']

key=len orders by length → ['a', 'c', 'bb']; the plain sort compares characters → ['a', 'bb', 'c'].

Share your result

Challenge a friend — the link contains the question, never the answer:

Copied ✓

Keep practising this rule

More output questions → All interactive problems

Questions this page answers

Why does 'Alpha' come before 'beta'?

Default string comparison uses code points: uppercase A–Z are 65–90 and lowercase a–z are 97–122. For dictionary order pass key=str.lower.

Which one should I use in an exam answer?

State the object story: sort() = in place, returns None; sorted() = returns a new list, original untouched. Marks are usually lost on the return value, not the ordering.