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

  1. Check the payload before calling: `if not data: return None` (an empty tree deserializes to no root)
  2. Validate at the I/O boundary — reject empty files/responses before they reach the deserializer
  3. 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

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


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/54176c845311a5ec. Report an issue: GitHub.