Sorting with sorted() & key

Sorting in Python means ordering items with sorted() (which returns a new list) or list.sort() (which sorts in place), optionally guided by a key function that decides what to sort by.

Learn Sorting with sorted() & key in our free Python course — an interactive lesson with runnable examples, a practice exercise and a quick reference.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Master the key argument and you can order anything — words by length, records by a field, or by several fields at once — using Python's fast, stable sort.

sorted() hands back a new list and leaves the original alone; .sort() rearranges the list in place and returns None :

The key function tells Python what to sort by. It's called once per item, and the items are ordered by those computed values:

The elements themselves are never modified — key only computes the value to compare by . The returned list still holds your original items, just reordered.

The operator module gives clean, fast key functions, and returning a tuple sorts by multiple fields at once:

Python's sort is stable : items that compare equal keep their original order. That lets you sort in stages — minor key first, then major key:

Because equal elements never get shuffled, a second sort only reorders what the first one tied on. This staged approach is often clearer than one giant tuple key.

Replace each ___ to complete the sorts so the output matches.

✅ .sort() returns None . Call it on its own line, or use nums = sorted(nums) .

✅ Pass the function object: key=len , not key=len(...) . Python calls it for each item.

✅ Give a key that maps everything to a comparable type, e.g. key=str , or clean the data first.

Build a leaderboard: highest score first, ties broken alphabetically by name.

Go deeper with the official Python documentation:

Lesson complete — you can order anything!

You know sorted() returns a new list while .sort() mutates in place, you can reverse, sort by a key (lambda, itemgetter , attrgetter ), break ties with a tuple key, and lean on Python's stable sort for multi-pass ordering.

🚀 Up next: Checkpoint — Core Syntax — put slicing, truthiness, unpacking, match, and sorting together in one build.

Practice quiz

What does sorted() return?

  • None, after sorting in place
  • The original list, now sorted
  • A brand-new sorted list, leaving the original untouched
  • A sorted tuple

Answer: A brand-new sorted list, leaving the original untouched. sorted() returns a new sorted list and does not modify the original iterable.

What does list.sort() return?

  • None
  • A new sorted list
  • The sorted list
  • The number of items sorted

Answer: None. .sort() sorts the list in place and returns None — never write x = x.sort().

What does sorted([3, 1, 2], reverse=True) produce?

reverse=True sorts in descending order, giving [3, 2, 1].

What is the role of the key argument?

  • It filters out elements that don't match
  • It is a function applied to each element to decide what to sort BY
  • It sets the sort algorithm
  • It reverses the order

Answer: It is a function applied to each element to decide what to sort BY. key=f computes f(item) for each element and sorts by those values; the elements themselves are unchanged.

What does sorted(['banana','kiwi','apple','fig'], key=len) return?

  • fig
  • kiwi
  • apple
  • banana

Answer: fig. Sorting by len orders by string length: fig(3), kiwi(4), apple(5), banana(6).

How do you sort by multiple fields at once?

  • Call sorted() twice with the same key
  • Pass reverse=True
  • Return a tuple from the key function
  • Use key=str only

Answer: Return a tuple from the key function. Returning a tuple like (p.last, p.first) makes Python compare element by element — primary then tie-breaker.

What does it mean that Python's sort is 'stable'?

  • It never crashes
  • Equal elements keep their original relative order
  • It always uses the same amount of memory
  • It sorts numbers before strings

Answer: Equal elements keep their original relative order. Stability means items that compare equal stay in their original order, which enables multi-pass sorting.

To rank by score descending then name ascending, which key works?

  • key=lambda p: (p.score, p.name)
  • key=lambda p: (p.name, p.score), reverse=True
  • key=lambda p: p.score, p.name
  • key=lambda p: (-p.score, p.name)

Answer: key=lambda p: (-p.score, p.name). Negating the numeric score flips just that field to descending while name stays ascending.

Why does sorted([3, 'a', 1]) raise a TypeError?

  • The list is too short
  • '<' is not supported between instances of int and str
  • sorted() needs a key argument
  • Lists cannot contain strings

Answer: '<' is not supported between instances of int and str. Python can't compare int and str directly. Provide a key that maps everything to a comparable type.

Which is true about sorted() vs .sort() regarding inputs?

  • Both work on any iterable
  • .sort() works on any iterable; sorted() is list-only
  • sorted() works on any iterable; .sort() is a list-only method
  • Neither works on strings

Answer: sorted() works on any iterable; .sort() is a list-only method. sorted() accepts any iterable (e.g. a string) and returns a list; .sort() exists only on lists.