Coding Interview Prep · Lesson

Custom Order with functools.cmp_to_key

Write a comparator when keys fall short.

Lesson 3 of 413 steps

Custom Order with functools.cmp_to_key is a free Coding Interview Prep lesson on CoddyKit. This is lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Coding Interview Prep learning path, and your progress syncs across the web and the CoddyKit app. The Coding Interview Prep course includes 4 lessons in total.

When a key Cannot Express It

Some orders depend on comparing two items together, not one value each. For those, you write a comparator function instead of a key.

What a Comparator Returns

A comparator takes two items a and b. Return a negative number if a comes first, positive if b comes first, and zero if they tie.

def cmp(a, b):
    if a < b: return -1
    if a > b: return 1
    return 0

Bridge It with cmp_to_key

Python sort only accepts a key, so wrap your comparator with functools.cmp_to_key to turn it into a usable key.

from functools import cmp_to_key
items.sort(key=cmp_to_key(cmp))

Classic Largest-Number Problem

To glue numbers into the biggest string, compare pairs by which concatenation is larger. A plain key cannot capture this.

def cmp(a, b):
    return (a + b < b + a) - (a + b > b + a)

Read That Compare Trick

The expression returns -1 when a+b is the bigger glue, so a sorts before b. That builds the largest possible number.

nums = ["3", "30", "34"]
nums.sort(key=cmp_to_key(cmp))
print("".join(nums))   # 34330

Sign Is What Matters

Sorting reads only the sign of the result. Returning -2 or -100 behaves the same as -1, so do not stress about exact magnitude.

Keep Comparators Consistent

Your comparator must be consistent: if a beats b and b beats c, then a must beat c. Contradictions give garbage order.

Prefer key When Possible

A key is computed once per item, but a comparator runs on many pairs and is slower. Use cmp_to_key only when a key truly cannot work.

The Subtraction Shortcut

For numeric comparisons you can return a - b directly, since its sign already encodes the order. Short and safe for ints.

items.sort(key=cmp_to_key(lambda a, b: a - b))

Watch Out for Floats

With floats, a - b can round to a tiny value or zero. Compare with explicit branches to avoid wrong ties.

Comparators Unlock Custom Orders

Concatenation order, custom rankings, and rule-based ties all become possible. A comparator is your escape hatch for tricky sorts.

Quick Check

Your comparator returns a negative number for cmp(a, b).

Recap

You can wrap a comparator with cmp_to_key for orders a key cannot express. Return a sign, stay consistent, and prefer keys when you can. 🧩

Free to start

Learn Coding Interview Prep with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
90
Lessons
360

Frequently Asked Questions

Is the “Custom Order with functools.cmp_to_key” lesson free?

Yes — the full text of “Custom Order with functools.cmp_to_key” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Coding Interview Prep course, upgrade to CoddyKit PRO. The Coding Interview Prep course includes 4 lessons in total.

What will I learn in “Custom Order with functools.cmp_to_key”?

Write a comparator when keys fall short. You practise Coding Interview Prep with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Coding Interview Prep?

No prior experience is required. Coding Interview Prep on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Custom Order with functools.cmp_to_key” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Coding Interview Prep lesson?

Yes. Every Coding Interview Prep lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. sorted() and the key Function
  2. Sort by Multiple Fields
  3. Custom Order with functools.cmp_to_key
  4. Why Sorting First Unlocks Solutions
← Back to Coding Interview Prep