donnemartin/interactive-coding-challenges · error · TypeError

nums cannot be None

Error message

nums cannot be None

What it means

Raised by Solution.move_zeroes when nums is None. The method rewrites nonzero elements in place over the front of the list and fills the tail with zeroes, so it needs a real list object. The guard converts an opaque 'NoneType has no len' failure into a clear message.

Source

Thrown at online_judges/move_zeroes/move_zeroes_solution.ipynb:135

  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution(object):\n",
    "\n",
    "    def move_zeroes(self, nums):\n",
    "        if nums is None:\n",
    "            raise TypeError('nums cannot be None')\n",
    "        pos = 0\n",
    "        for num in nums:\n",
    "            if num != 0:\n",
    "                nums[pos] = num\n",
    "                pos += 1\n",
    "        if pos < len(nums):\n",
    "            nums[pos:] = [0] * (len(nums) - pos)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Unit Test"
   ]
  },
  {
   "cell_type": "code",

View on GitHub (pinned to 358f2cc604)

Solutions

  1. Pass an empty list instead of None for 'no input'.
  2. Check nums is not None at the call site before invoking.
  3. If None is expected occasionally, wrap the call in try/except TypeError and skip.

Example fix

# before
Solution().move_zeroes(nums)  # nums is None

# after
if nums is not None:
    Solution().move_zeroes(nums)
Defensive patterns

Strategy: type-guard

Validate before calling

if nums is None:
    nums = []
Solution().move_zeroes(nums)

Type guard

def is_num_list(x):
    return isinstance(x, list) and all(isinstance(n, (int, float)) for n in x)

Try / catch

try:
    Solution().move_zeroes(nums)
except TypeError as e:
    if 'cannot be None' in str(e):
        nums = []
    else:
        raise

Prevention

When it happens

Trigger: Calling move_zeroes(None), or passing a value that is None because the source list failed to load.

Common situations: In-place array manipulation interview problem where the input comes from optional parsed data; forgetting a None default check before calling.

Related errors


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