donnemartin/interactive-coding-challenges · error · TypeError
data cannot be None
Error message
data cannot be None
What it means
QuickSort.sort raises TypeError('data cannot be None') as an explicit guard before delegating to the recursive _sort. Without it, len(data) inside _sort would raise an AttributeError on None. Only None is rejected; an empty list is valid and returned as-is.
Source
Thrown at sorting_searching/quick_sort/quick_sort_solution.ipynb:113
"metadata": {},
"source": [
"## Code"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from __future__ import division\n",
"\n",
"\n",
"class QuickSort(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",
" equal = []\n",
" left = []\n",
" right = []\n",
" pivot_index = len(data) // 2\n",
" pivot_value = data[pivot_index]\n",
" # Build the left and right partitions\n",
" for item in data:\n",
" if item == pivot_value:\n",
" equal.append(item)\n",
" elif item < pivot_value:\n",
" left.append(item)\n",
" else:\n",
" right.append(item)\n",View on GitHub (pinned to 358f2cc604)
Solutions
- Pass a list (use data or [] if None means empty) before calling sort()
- Guard the call site: if data is not None: result = qs.sort(data)
- Fix the upstream code that produced None instead of a list
Example fix
// before result = QuickSort().sort(data) # data may be None // after result = QuickSort().sort(data) if data is not None else []
Defensive patterns
Strategy: validation
Validate before calling
if data is None:
data = []
result = QuickSort().sort(data) Type guard
def is_sortable(x):
return isinstance(x, list) Try / catch
try:
result = qs.sort(data)
except TypeError as e:
if 'cannot be None' in str(e):
result = []
else:
raise Prevention
- Default optional data params to [] not None
- Validate function arguments at call boundary
- Normalize None to [] right after loading data
When it happens
Trigger: Calling QuickSort().sort(None), or passing a None-valued variable (failed load, unset default parameter, conditional that never assigned a list).
Common situations: Optional config/data that defaults to None; empty results from a database query being confused with None; tests exercising invalid input.
Related errors
- array cannot be None
- sentence cannot be None
- rows and cols cannot be None
- s or t cannot be None
- a or b cannot be None
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/54748ebc4ab3de0c.
Report an issue: GitHub.