pola-rs/polars · error
range end index out of range for slice of length
Error message
range end index {end} out of range for slice of length {len} What it means
slice_index_fail panics when a range's end exceeds the slice length. This mirrors the standard library's slice bounds message and is reached through polars' check_range helper when a caller requests a slice extending past the end of the underlying data.
Solutions
- Clamp end to the collection length: end.min(len)
- Pre-check end <= len and return an empty/truncated result instead
- Use saturating/checked range construction before calling APIs that slice
- Fix the upstream length source so the requested end reflects actual data size
Example fix
// before let out = check_range(start..end, ..len); // after let end = end.min(len); let out = check_range(start..end, ..len);
Defensive patterns
Strategy: validation
Validate before calling
def safe_end(end, len_):
if end > len_:
raise IndexError(f"range end {end} out of range for slice of length {len_}")
return end
# or clamp: end = min(end, len_) Prevention
- Always clamp end with min(end, len)
- Never assume a minimum collection size when paginating
- Use checked range helpers consistently
- Recompute lengths immediately before slicing
When it happens
Trigger: Slicing via check_range with an end index greater than the collection length, e.g. asking for rows 5..100 on a 50-row frame segment.
Common situations: Hardcoded slice windows computed from stale lengths; pagination that assumes a minimum record count; taking n..end ranges without knowing size.
Related errors
- range start index out of range for slice of length
- slice index starts at
- activate dtype
- addition overflow: +
- can only use timedelta string language with…
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/2db30daa8a8deb06.
Report an issue: GitHub.
Appendix: source
Thrown at crates/polars-utils/src/range.rs:10
use std::ops;
// Copied from the stdlib.
fn slice_index_fail(start: usize, end: usize, len: usize) -> ! {
if start > len {
panic!("range start index {start} out of range for slice of length {len}",)
}
if end > len {
panic!("range end index {end} out of range for slice of length {len}",)
}
if start > end {
panic!("slice index starts at {start} but ends at {end}",)
}
// Only reachable if the range was a `RangeInclusive` or a
// `RangeToInclusive`, with `end == len`.
panic!("range end index {end} out of range for slice of length {len}",)
}
#[must_use]
pub fn check_range<R>(range: R, bounds: ops::RangeTo<usize>) -> ops::Range<usize>
where
R: ops::RangeBounds<usize>,
{
let len = bounds.end;
let end = match range.end_bound() {View on GitHub (pinned to fe841f959e)