TheAlgorithms/Python · error · ValueError
Data cannot be empty.
Error message
Data cannot be empty.
What it means
Raised by deserialize(data) (serialize_deserialize_binary_tree.py) when data is empty (or otherwise falsy, e.g. None). The serialized form is a comma-separated preorder string like '1,2,null,null,3,null,null'; an empty string yields no tokens and the recursive build_tree would fail incoherently, so the function guards with ValueError('Data cannot be empty.') up front.
Source
Thrown at data_structures/binary_tree/serialize_deserialize_binary_tree.py:117
>>> root == deserialized
True
>>> root is deserialized # two separate trees
False
>>> root.right.right.value = 6
>>> root == deserialized
False
>>> serialzed_data = repr(root)
>>> deserialized = deserialize(serialzed_data)
>>> root == deserialized
True
>>> deserialize("")
Traceback (most recent call last):
...
ValueError: Data cannot be empty.
"""
if not data:
raise ValueError("Data cannot be empty.")
# Split the serialized string by a comma to get node values
nodes = data.split(",")
def build_tree() -> TreeNode | None:
# Get the next value from the list
value = nodes.pop(0)
if value == "null":
return None
node = TreeNode(int(value))
node.left = build_tree() # Recursively build left subtree
node.right = build_tree() # Recursively build right subtree
return node
return build_tree()
View on GitHub (pinned to f5988cc097)
Solutions
- Check the payload before calling: `if not data: return None` (an empty tree deserializes to no root)
- Validate at the I/O boundary — reject empty files/responses before they reach the deserializer
- Strip carefully: `data = data.strip()` then branch on emptiness rather than passing whitespace
Example fix
# before tree = deserialize(open(path).read()) # empty file -> ValueError # after raw = open(path).read().strip() tree = deserialize(raw) if raw else None
Defensive patterns
Strategy: validation
Validate before calling
data = data.strip() if isinstance(data, str) else data root = deserialize(data) if data else None
Type guard
def is_serialized_payload(data: object) -> bool:
return isinstance(data, str) and len(data) > 0 and data.split(',')[0] not in ('', 'null') Try / catch
try:
root = deserialize(data)
except ValueError:
root = None # empty serialized tree Prevention
- Strip and check emptiness after every file/network read that feeds deserialize
- Treat empty payload as an empty tree (None root) at the caller
- Round-trip test serialize(deserialize(s)) to catch corrupted payloads early
When it happens
Trigger: deserialize(''); deserialize(None) after repr() of a None root or a failed read; feeding an empty file/network response into the function; whitespace-only string is NOT caught (only falsy values) and will fail later at int('').
Common situations: Round-tripping trees through files that may be empty; API endpoints returning empty bodies; str.strip() applied before deserialize leaving ''.
Related errors
- Empty string was passed to the function
- Empty string was passed to the function
- Vector is empty
- Matrix has no element
- number must be positive
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/54176c845311a5ec.
Report an issue: GitHub.