TheAlgorithms/Python · error · ValueError
The array is empty.
Error message
The array is empty.
What it means
Raised by PrefixSum.get_sum() in data_structures/arrays/prefix_sum.py when the underlying prefix_sum list is empty — i.e. the PrefixSum was built (directly or effectively) from an empty array. The emptiness check runs before the range check, so any get_sum call on an empty structure raises this first.
Source
Thrown at data_structures/arrays/prefix_sum.py:51
>>> PrefixSum([]).get_sum(0, 0)
Traceback (most recent call last):
...
ValueError: The array is empty.
>>> PrefixSum([1,2,3]).get_sum(-1, 2)
Traceback (most recent call last):
...
ValueError: Invalid range specified.
>>> PrefixSum([1,2,3]).get_sum(2, 3)
Traceback (most recent call last):
...
ValueError: Invalid range specified.
>>> PrefixSum([1,2,3]).get_sum(2, 1)
Traceback (most recent call last):
...
ValueError: Invalid range specified.
"""
if not self.prefix_sum:
raise ValueError("The array is empty.")
if start < 0 or end >= len(self.prefix_sum) or start > end:
raise ValueError("Invalid range specified.")
if start == 0:
return self.prefix_sum[end]
return self.prefix_sum[end] - self.prefix_sum[start - 1]
def contains_sum(self, target_sum: int) -> bool:
"""
The function returns True if array contains the target_sum,
False otherwise.
Runtime : O(n)
Space: O(n)
>>> PrefixSum([1,2,3]).contains_sum(6)View on GitHub (pinned to f5988cc097)
Solutions
- Check the source array is non-empty before constructing/querying: if data: ps = PrefixSum(data).
- Ensure queries only run after data population completes (ordering, readiness flag).
- Return a sentinel (0 or None) for empty data instead of calling get_sum.
Example fix
# before
ps = PrefixSum([])
total = ps.get_sum(0, 0) # ValueError
# after
total = 0 # defined result for empty range
data = [x for x in source if keep(x)]
if data:
total = PrefixSum(data).get_sum(0, len(data) - 1) Defensive patterns
Strategy: validation
Validate before calling
if not data:
return 0 # no data, no range sums
ps = PrefixSum(data)
total = ps.get_sum(0, len(data) - 1) Prevention
- Only construct/query PrefixSum after data is populated
- Check emptiness once at construction, not per query
When it happens
Trigger: Calling PrefixSum([]).get_sum(0, 0), or calling get_sum before any data was loaded into the structure. Empty arrays passed to the constructor produce an empty prefix_sum list.
Common situations: Querying a prefix-sum structure that was initialized but not yet populated, datasets that load asynchronously where a query races ahead of the data load, or empty query windows in data pipelines.
Related errors
- Invalid range specified.
- The parameter s must not be empty.
- The parameter bwt_string must not be empty.
- We need some text to work with.
- empty number list not allowed
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/12ce451f4da2abe8.
Report an issue: GitHub.