donnemartin/interactive-coding-challenges · error · TypeError
items cannot be None
Error message
items cannot be None
What it means
Raised by Anagram.group_anagrams when items is None. The method iterates items and builds an OrderedDict keyed by sorted character tuples, so a None list is rejected up front with a TypeError instead of failing inside the for loop.
Source
Thrown at sorting_searching/anagrams/anagrams_solution.ipynb:111
"metadata": {},
"source": [
"## Code"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from collections import OrderedDict\n",
"\n",
"\n",
"class Anagram(object):\n",
"\n",
" def group_anagrams(self, items):\n",
" if items is None:\n",
" raise TypeError('items cannot be None')\n",
" if not items:\n",
" return items\n",
" anagram_map = OrderedDict()\n",
" for item in items:\n",
" # Use a tuple, which is hashable and\n",
" # serves as the key in anagram_map\n",
" sorted_chars = tuple(sorted(item))\n",
" if sorted_chars in anagram_map:\n",
" anagram_map[sorted_chars].append(item)\n",
" else:\n",
" anagram_map[sorted_chars] = [item]\n",
" result = []\n",
" for value in anagram_map.values():\n",
" result.extend(value)\n",
" return result"
]
},
{View on GitHub (pinned to 358f2cc604)
Solutions
- Default to an empty list: items = items or []
- Fix loaders to return [] instead of None on missing data
- Check the source collection before calling
Example fix
// before groups = anagram.group_anagrams(load_words(path)) // after groups = anagram.group_anagrams(load_words(path) or [])
Defensive patterns
Strategy: validation
Validate before calling
items = items or [] anagram.group_anagrams(items)
Type guard
def is_str_list(x):
return isinstance(x, list) and all(isinstance(i, str) for i in x) Try / catch
try:
anagram.group_anagrams(words)
except TypeError:
groups = {} Prevention
- Loaders return [] for missing word lists
- Avoid None-returning chain steps
When it happens
Trigger: Calling group_anagrams(None). An empty list is valid and returned as-is; only None raises.
Common situations: Word lists loaded from a file or API where the words field is missing; a list comprehension variable that stayed None; chaining after a function that returns None on failure.
Related errors
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/0e6824e773008640.
Report an issue: GitHub.