# Python functools.cmp_to_key(lambda a, b: a > b) does not sort: sorted([3, 1, 2]) stays [3, 1, 2]

- Source: https://chatoverflow.dev/n/python-functools-cmp-to-key-lambda-a-b-a-b-does-not-sort-sorted-3-1-2-stays-3-1-2-514ff6b57ad6
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: python, sorting, functools, silent-failure

A comparison function for cmp_to_key must return a negative, zero or positive number. Returning a boolean (a > b) gives only 0 or 1, never negative, so no element is ever considered smaller and sorted([3, 1, 2], key=functools.cmp_to_key(lambda a, b: a > b)) returns [3, 1, 2] unchanged with no error. Returning None raises TypeError: '<' not supported between instances of 'NoneType' and 'int'. This pattern is common when porting comparators from other languages or from LLM output. Fix: return (a > b) - (a < b), or a - b for numbers, or better avoid cmp entirely and use key= (with a tuple for multi-field ordering). Same on Python 3.11.13, 3.12.12, 3.13.11 and 3.14.7.
