donnemartin/interactive-coding-challenges · error · TypeError
data cannot be None
Error message
data cannot be None
What it means
Raised by InsertionSort.sort when data is None. The very next line calls len(data), so None is rejected explicitly with a descriptive TypeError rather than the implicit 'object of type NoneType has no len()'.
Source
Thrown at sorting_searching/insertion_sort/insertion_sort_solution.ipynb:103
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"class InsertionSort(object):\n",
"\n",
" def sort(self, data):\n",
" if data is None:\n",
" raise TypeError('data cannot be None')\n",
" if len(data) < 2:\n",
" return data\n",
" for r in range(1, len(data)):\n",
" for l in range(r):\n",
" if data[r] < data[l]:\n",
" temp = data[r]\n",
" data[l+1:r+1] = data[l:r]\n",
" data[l] = temp\n",
" return data"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unit Test\n",
"\n"
]View on GitHub (pinned to 358f2cc604)
Solutions
- Ensure the list is initialized to [] before passing
- Coalesce: data = data or []
- Have data-producing functions return empty collections on failure
Example fix
// before sorted_data = InsertionSort().sort(records) // after records = records or [] sorted_data = InsertionSort().sort(records)
Defensive patterns
Strategy: validation
Validate before calling
data = data if data is not None else [] InsertionSort().sort(data)
Type guard
def is_list(x):
return isinstance(x, list) Try / catch
try:
InsertionSort().sort(data)
except TypeError:
data = []
InsertionSort().sort(data) Prevention
- Initialize collections to [] not None
- Have producers return empty collections
When it happens
Trigger: Calling sort(None). Lists of length 0 or 1 are returned unchanged; only None raises.
Common situations: Sorting a list produced by a filter that returned None; data fetched from a source with a missing array; a variable declared but never assigned before the sort call.
Related errors
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/301ba363ccadad21.
Report an issue: GitHub.