donnemartin/interactive-coding-challenges · error · TypeError

prices cannot be None

Error message

prices cannot be None

What it means

Raised by Solution.find_max_profit when prices is None. The method calls len(prices) and pops from it, which would fail on None; the guard requires a list of prices. Note a list with fewer than 2 values is a separate ValueError.

Source

Thrown at online_judges/max_profit/max_profit_solution.ipynb:103

   "metadata": {},
   "source": [
    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "\n",
    "class Solution(object):\n",
    "\n",
    "    def find_max_profit(self, prices):\n",
    "        if prices is None:\n",
    "            raise TypeError('prices cannot be None')\n",
    "        if len(prices) < 2:\n",
    "            raise ValueError('prices must have at least two values')\n",
    "        min_price = prices.pop(0)\n",
    "        max_profit = prices[0] - min_price\n",
    "        for price in prices:\n",
    "            profit = price - min_price\n",
    "            min_price = min(price, min_price)\n",
    "            max_profit = max(profit, max_profit)\n",
    "        return max_profit"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Unit Test"
   ]
  },

View on GitHub (pinned to 358f2cc604)

Solutions

  1. Pass a list with at least two prices
  2. Make your data loader return [] (and handle it) rather than None
  3. Guard: if prices: solution.find_max_profit(prices)

Example fix

# before
prices = fetch_prices(symbol)  # returns None on API error
solution.find_max_profit(prices)

# after
prices = fetch_prices(symbol)
if prices is None:
    prices = []
if len(prices) >= 2:
    solution.find_max_profit(prices)
Defensive patterns

Strategy: validation

Validate before calling

prices = prices or []
if len(prices) >= 2: solution.find_max_profit(prices)

Type guard

def is_price_list(x): return isinstance(x, list) and len(x) >= 2

Try / catch

try:
    p = solution.find_max_profit(prices)
except (TypeError, ValueError) as e:
    p = 0
    logger.warning(e)

Prevention

When it happens

Trigger: Calling find_max_profit(None) — e.g. a market-data fetch returned None on error, or the prices variable was never populated before the call.

Common situations: API/DB fetchers that return None instead of [] on failure or empty results; tests of the guards; notebook cells run out of order.

Related errors


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