donnemartin/interactive-coding-challenges · error · TypeError

data cannot be None

Error message

data cannot be None

What it means

MergeSort.sort raises TypeError('data cannot be None') when the input to sort() is None. It is an explicit input-validation guard at the public API boundary before the recursive _sort runs. Passing None would otherwise fail deeper with a confusing 'len(None)' AttributeError.

Source

Thrown at sorting_searching/merge_sort/merge_sort_solution.ipynb:112

   "metadata": {},
   "source": [
    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import division\n",
    "\n",
    "\n",
    "class MergeSort(object):\n",
    "\n",
    "    def sort(self, data):\n",
    "        if data is None:\n",
    "            raise TypeError('data cannot be None')\n",
    "        return self._sort(data)\n",
    "\n",
    "    def _sort(self, data):\n",
    "        if len(data) < 2:\n",
    "            return data\n",
    "        mid = len(data) // 2\n",
    "        left = data[:mid]\n",
    "        right = data[mid:]\n",
    "        left = self._sort(left)\n",
    "        right = self._sort(right)\n",
    "        return self._merge(left, right)\n",
    "\n",
    "    def _merge(self, left, right):\n",
    "        l = 0\n",
    "        r = 0\n",
    "        result = []\n",
    "        while l < len(left) and r < len(right):\n",
    "            if left[l] < right[r]:\n",

View on GitHub (pinned to 358f2cc604)

Solutions

  1. Ensure the caller passes a real list, e.g. data = data or [] before calling sort()
  2. Add a None check in your own code and skip/short-circuit sorting when data is None
  3. If None should be treated as empty, wrap: sorted_data = ms.sort(data) if data is not None else []

Example fix

// before
result = MergeSort().sort(data)  # data may be None

// after
result = MergeSort().sort(data if data is not None else [])
Defensive patterns

Strategy: validation

Validate before calling

if data is None:
    data = []
result = MergeSort().sort(data)

Type guard

def is_sortable(x):
    return isinstance(x, list) and x is not None

Try / catch

try:
    result = ms.sort(data)
except TypeError as e:
    if 'cannot be None' in str(e):
        result = []
    else:
        raise

Prevention

When it happens

Trigger: Calling MergeSort().sort(None), or passing a variable that was initialized to None / failed to load (e.g. a parsed dataset or API response that came back empty) into sort().

Common situations: Data pipelines where an upstream fetch or file read returns None; unit tests that exercise None handling; refactors that make a data argument optional without a default empty list.

Related errors


AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28). Data as JSON: /api/errors/d70bf7fb9aa0b847. Report an issue: GitHub.