donnemartin/interactive-coding-challenges · error · TypeError
grid cannot be None
Error message
grid cannot be None
What it means
Raised by Solution.island_perimeter when grid is None. The method immediately does len(grid) and len(grid[0]), which would raise TypeError on None; the guard states the contract: a 2D list of 0/1 cells is required.
Source
Thrown at online_judges/island_perimeter/island_perimeter_solution.ipynb:105
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"class Solution(object):\n",
"\n",
" def island_perimeter(self, grid):\n",
" if grid is None:\n",
" raise TypeError('grid cannot be None')\n",
" sides = 0\n",
" num_rows = len(grid)\n",
" num_cols = len(grid[0])\n",
" for i in range(num_rows):\n",
" for j in range(num_cols):\n",
" if grid[i][j] == 1:\n",
" # Check left\n",
" if j == 0 or grid[i][j - 1] == 0:\n",
" sides += 1\n",
" # Check right\n",
" if j == num_cols - 1 or grid[i][j + 1] == 0:\n",
" sides += 1\n",
" # Check up\n",
" if i == 0 or grid[i - 1][j] == 0:\n",
" sides += 1\n",
" # Check down\n",
" if i == num_rows - 1 or grid[i + 1][j] == 0:\n",
" sides += 1\n",View on GitHub (pinned to 358f2cc604)
Solutions
- Pass a well-formed 2D list, e.g. [[0,1,0,0],[1,1,1,0],...]
- Default the loader to [] or fail loudly when the grid source is missing
- Ensure the notebook cell building the grid has executed before the call
Example fix
# before
solution.island_perimeter(grid) # grid never assigned / loader returned None
# after
grid = load_grid(path)
if grid is None:
raise FileNotFoundError(path)
solution.island_perimeter(grid) Defensive patterns
Strategy: validation
Validate before calling
if grid is None: raise ValueError('grid is required')
solution.island_perimeter(grid) Type guard
def is_grid(g): return isinstance(g, list) and all(isinstance(r, list) for r in g)
Try / catch
try:
p = solution.island_perimeter(grid)
except TypeError as e:
raise ValueError('missing grid input') from e Prevention
- Run notebook cells that build inputs before using them
- Have grid loaders fail loudly on missing sources
When it happens
Trigger: Calling island_perimeter(None) — e.g. a matrix loader returned None, or grid came from a failed parse or an optional parameter.
Common situations: Reading grids from files/APIs that may be absent; tests exercising the None guard; notebooks where the cell defining the grid wasn't run.
Related errors
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/a3346f8084414aa1.
Report an issue: GitHub.