Python: Use slice.indices results as range arguments
slice.indices(length) resolves omitted and out-of-range bounds for a sequence of known length. Use the returned triple with range() when you need the selected positions, especially for a negative step.
Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.
Run the example
Save this as slice_positions_demo.py in an empty working directory:
values = ["a", "b", "c", "d"]
selection = slice(None, None, -1)
bounds = selection.indices(len(values))
positions = list(range(*bounds))
print("Bounds:", bounds)
print("Positions:", positions)
print("Selected:", [values[index] for index in positions])
print("Original slice:", values[selection])
print("Reused as slice:", values[slice(*bounds)])
assert [values[index] for index in positions] == values[selection]Run it without -O so any assertions remain enabled:
python3 slice_positions_demo.pyCaptured output:
Bounds: (3, -1, -1)
Positions: [3, 2, 1, 0]
Selected: ['d', 'c', 'b', 'a']
Original slice: ['d', 'c', 'b', 'a']
Reused as slice: []The normalized stop of -1 means that range() stops before index -1. Passing it back to a slice changes its meaning: the slice interprets -1 relative to the sequence’s end. In this example that produces an empty result.
Limits and cleanup
Keep the original slice for slicing, and use normalized bounds only for index iteration against the same sequence length. Recompute them if the sequence length changes. A zero step is invalid and raises ValueError; normalization does not make it valid.
After testing, remove the example script from its working directory:
rm -- slice_positions_demo.pyReference
Acknowledgements
This post was created with assistance from AI.