← Back

Home β€Ί Problems β€Ί TypeError: sorting mixed text + numbers

TypeError: sorting mixed text + numbers

πŸ› Fix the bug Topic: sorting Difficulty: easy Free

What this problem practises

The two sorting APIs are not interchangeable: sorted() returns a brand-new list while list.sort() sorts in place and returns None. Key functions compare the values they extract, and comparing mixed types raises TypeError.

This is a fix-the-bug problem: a short program is given in its broken state, and the task is to repair the code so it produces the required output. The interactive editor runs your fixed version in the browser and checks it for you β€” no setup, no local interpreter.

Difficulty: easy β€” the fix or the trick is normally a single line, and a careful read should be enough.

The challenge

This program crashes with TypeError because text and numbers cannot be compared. Remove the words so it prints [2, 50].

The code runs in PyDebug’s in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.

The error it raises

Run the broken snippet and Python stops with this exact error: TypeError: '<' not supported between instances of 'str' and 'int'. Match it to the Python errors guide, then repair the line that produced it β€” knowing the message is half the fix.

The snippet

The interactive editor pre-fills exactly this code, broken and ready to repair:

nums = [2, 'grape', 50, 'dog']
nums.sort()
print(nums)

Understand the rule

Python 3 refuses to guess whether `'10'` is less than or greater than `2` (alphabetically `'10' < '2'`, numerically `10 > 2`). Sorting a heterogeneous list like `[3, '1', 2]` triggers `TypeError: '<' not supported between instances of 'str' and 'int'` on the first cross-type comparison.

How to trace it

  1. `sorted(items)` or `items.sort()` runs Timsort, comparing adjacent elements with `<`.
  2. As soon as Timsort compares a `str` element against an `int` element, neither `str.__lt__` nor `int.__gt__` accepts the other type.
  3. Both return `NotImplemented`, and Python raises `TypeError: '<' not supported between instances of 'str' and 'int'`.
  4. Normalize types first (`[int(x) for x in items]`) or supply a consistent sort key (`sorted(items, key=int)` or `sorted(items, key=str)`).

Common wrong fixes

Rule to remember

Every element compared during sorting must share a compatible order β€” pass `key=int` for numeric ordering or convert mixed inputs upfront.

Solve it in the interactive editor β†’

More sorting problems

Keep going