Skip to the solution
EasyDSA6 min read

How do you sort with a custom key, and how does sorted differ from sort?

404 views

The problem

Question presented to candidate: "Say you have a list of employee records and need them ordered by team, and then by salary from highest to lowest. How would you sort that in Python? And while you are at it β€” what is the difference between sorted() and list.sort()?"

What a strong answer should cover:

  • sorted(iterable) returns a new list from any iterable; list.sort() sorts the list in place, exists only on lists and returns None.
  • key= takes a one-argument function, called once per element; the elements are ordered by those key values (key=len, key=str.lower, operator.itemgetter, lambda).
  • Tuple keys for multi-level ordering, negating numbers for a descending part, or several passes from the least to the most important key.
  • Both are stable (equal keys keep their original order), and reverse=True keeps that stability, unlike reversing the result afterwards.
  • Edge cases: mixed types raise TypeError in Python 3, None values need a key, old comparison functions go through functools.cmp_to_key.
  • Cost: O(n log n) comparisons in general, about n - 1 on already-ordered input (Timsort finds existing runs).

Clarifying questions expected:

  • "Do we need to keep the original order of the list?" β€” decides between sorted() and .sort().
  • "How should ties and missing values be ordered?" β€” decides the key and whether stability matters.

Code / implementation expected: Yes β€” a sorted(..., key=...) with a tuple key, and a demonstration that .sort() returns None.

  • sorting

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythonsorted vs sort, key functions, dict by value, tuple keys
PythonKey calls, stability, reverse=True and comparison counts
PythonMixed types, None values, cmp_to_key and the modified-list error

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 26 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

How do you convert between Python objects and JSON?

Continue