TheAlgorithms/Python · error · ValueError
{var_name} must be a list
Error message
{var_name} must be a list What it means
Raised by viterbi's internal _validate_list (dynamic_programming/viterbi.py:278) when observations_space or states_space is not a Python list. The Viterbi implementation indexes and iterates these collections assuming list semantics, and the validator deliberately rejects other types (tuples, strings, sets, ints) with a message naming the offending parameter via var_name.
Source
Thrown at dynamic_programming/viterbi.py:278
_validate_list(observations_space, "observations_space")
_validate_list(states_space, "states_space")
def _validate_list(_object: Any, var_name: str) -> None:
"""
>>> _validate_list(["a"], "mock_name")
>>> _validate_list("a", "mock_name")
Traceback (most recent call last):
...
ValueError: mock_name must be a list
>>> _validate_list([0.5], "mock_name")
Traceback (most recent call last):
...
ValueError: mock_name must be a list of strings
"""
if not isinstance(_object, list):
msg = f"{var_name} must be a list"
raise ValueError(msg)
else:
for x in _object:
if not isinstance(x, str):
msg = f"{var_name} must be a list of strings"
raise ValueError(msg)
def _validate_dicts(
initial_probabilities: Any,
transition_probabilities: Any,
emission_probabilities: Any,
) -> None:
"""
>>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": 0.7}})
>>> _validate_dicts("invalid", {"d": {"e": 0.6}}, {"f": {"g": 0.7}})
Traceback (most recent call last):
...
ValueError: initial_probabilities must be a dictView on GitHub (pinned to f5988cc097)
Solutions
- Convert with list(...) at the call site: viterbi(list(observations_space), list(states_space), ...).
- For numpy arrays use .tolist() to get native Python str elements.
- Keep the HMM config format aligned with the API (JSON arrays deserialize to lists naturally).
Example fix
# before
viterbi(('walk','shop'), ['rainy','sunny'], initial_p, trans_p, emit_p) # ValueError
# after
viterbi(['walk','shop'], ['rainy','sunny'], initial_p, trans_p, emit_p) Defensive patterns
Strategy: type-guard
Validate before calling
def as_str_list(x) -> list[str] | None:
return list(x) if isinstance(x, (list, tuple, set)) and all(isinstance(i, str) for i in x) else None Type guard
def is_str_list(x: object) -> TypeGuard[list[str]]:
return isinstance(x, list) and all(isinstance(i, str) for i in x) Prevention
- Convert numpy arrays with .tolist() at the pipeline boundary.
- Standardize on plain lists for HMM symbol spaces.
- Keep config in JSON so arrays deserialize as lists.
When it happens
Trigger: Calling viterbi with observations_space=('rainy','sunny') (a tuple) or a numpy array instead of a list; passing a string like 'abcd' (a str is not a list); passing an int. The message interpolates the parameter name, e.g. 'observations_space must be a list'.
Common situations: Passing numpy array columns or pandas Series directly from a data pipeline without .tolist(); using tuples for 'immutability' in config; assuming duck typing accepts any iterable.
Related errors
- {var_name} must be a list of strings
- {var_name} must be a dict
- {var_name} all keys must be strings
- {var_name} {nested_text}all values must be {value_type.__nam
- There's an empty parameter
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/65242cad372ce84a.
Report an issue: GitHub.