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 returnsNone.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=Truekeeps that stability, unlike reversing the result afterwards. - Edge cases: mixed types raise
TypeErrorin Python 3,Nonevalues need a key, old comparison functions go throughfunctools.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.