donnemartin/interactive-coding-challenges · error · ValueError
nums cannot be empty
Error message
nums cannot be empty
What it means
Raised by Solution.two_sum when nums is an empty list. With no elements there can be no pair summing to target, and the implementation distinguishes 'no input' (ValueError) from 'no solution' (returns None). It fires after the None check, so nums must be non-None AND non-empty.
Source
Thrown at arrays_strings/two_sum/two_sum_solution.ipynb:168
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"class Solution(object):\n",
"\n",
" def two_sum(self, nums, target):\n",
" if nums is None or target is None:\n",
" raise TypeError('nums or target cannot be None')\n",
" if not nums:\n",
" raise ValueError('nums cannot be empty')\n",
" cache = {}\n",
" for index, num in enumerate(nums):\n",
" cache_target = target - num\n",
" if num in cache:\n",
" return [cache[num], index]\n",
" else:\n",
" cache[cache_target] = index\n",
" return None"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unit Test"
]
},
{View on GitHub (pinned to 358f2cc604)
Solutions
- Skip the call when the list is empty: if nums: result = two_sum(nums, target)
- Treat empty input as an explicit domain case in your handler (400 or empty result) rather than an exception
- Validate batch size before entering the two-sum step
Example fix
# before result = Solution().two_sum(nums, target) # nums may be [] # after result = Solution().two_sum(nums, target) if nums else None
Defensive patterns
Strategy: validation
Validate before calling
if nums:
Solution().two_sum(nums, target) Type guard
def is_non_empty_list(nums) -> bool:
return isinstance(nums, list) and len(nums) > 0 Try / catch
try:
Solution().two_sum(nums, target)
except ValueError as e:
if 'empty' in str(e):
return None
raise Prevention
- Guard empty batches before processing
- Treat empty input as a domain case, not an exception
When it happens
Trigger: Calling two_sum([], 9); filtering a list before passing it and ending up with zero elements; early-morning data loads producing empty inputs.
Common situations: Chained filters/comprehensions that can legitimately yield []; processing batches where some batches are empty; confusing 'empty input' with 'no answer found'.
Related errors
- nums or target cannot be None
- data cannot be None
- Invalid key
- num cannot be less than one
- str1 or str2 cannot be None
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/271506ae6c6d2424.
Report an issue: GitHub.