Loading section...

functools.cmp_to_key — When key= Isn't Enough

There's exactly one class of problem where a key= function can't solve the sort: when the comparison requires looking at two elements simultaneously. The canonical example is 'arrange these numbers to form the largest possible concatenated number.' You can't express that as a property of a single element. This is when functools.cmp_to_key appears — and interviewers at Amazon and Meta use this specific problem to test exactly this knowledge. The Largest Number Problem (Amazon / Meta Interview Staple) Version String Sorting — Another Classic cmp_to_key Case