Skip to content

Fix slicing with a negative step panicking and returning wrong items - #1002

Merged
mitsuhiko merged 1 commit into
mitsuhiko:mainfrom
lprnmns:slice-negative-step
Nov 5, 2026
Merged

mitsuhiko merged 1 commit into
mitsuhiko:mainfrom
lprnmns:slice-negative-step

Conversation

@lprnmns

@lprnmns lprnmns commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Slicing with a negative step computed its bounds differently from Python:

  • On an empty value, [][::-1] and ""[::-1] panic with "index out of bounds: the len is 0".
  • An explicit stop of 0 (or a negative stop that clamps to 0) was treated like a missing stop, so [1, 2, 3][:0:-1] returned [3, 2, 1] instead of [3, 2], and x[:-10:-1] on a list of 10 items included the first item.
  • A negative start past the beginning, e.g. [1, 2, 3][-100::-1], returned [1] instead of [].

range_step_backwards now clamps start and stop like Python (to -1..=len - 1) and walks down from start to stop, excluding stop. Positive steps are unchanged.

The new lines in tests/inputs/slicing.txt cover these cases; without the fix test_vm panics in ops.rs. I also compared the result against Python's slicing for lists of length 0, 1, 2 and 5 with all combinations of start/stop in None, -12, -6, -5, -4, -1, 0, 1, 2, 4, 5, 6, 12 and steps -1, -2, -3, -7, 1, 2, 3 (4732 cases) and they all match. The Go port already behaved like Python here.

@mitsuhiko
mitsuhiko merged commit 51fbfe3 into mitsuhiko:main Nov 5, 2026
23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants