Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Data types & structuresJuniorCommonPractical

How does Python slicing with `start:stop:step` work, including negative indices and negative steps?

Answer

A slice `sequence[start:stop:step]` returns a new sequence of the same type, for built-in sequences like `list`, `str` and `tuple`, containing elements from index `start` up to but not including `stop`, advancing by `step`; the exact return type and behavior for any given object is ultimately defined by that type's own `__getitem__`, so a custom or third-party sequence type could return something other than a plain copy, such as a view. Negative indices count from the end (`-1` is the last element), and a negative step reverses direction, so `stop` must logically come before `start` in iteration order. For the built-in sequence types, slicing never raises an IndexError for out-of-range bounds; it simply clamps them, which makes it safe for approximate ranges.

Strong answer includes

  • stop index is exclusive
  • negative indices count from the end
  • for built-in sequences out-of-range bounds are clamped, not errors; a custom type's __getitem__ could behave differently

Practical example

Python example
"hello world"[::-1]

reverses the string to `"dlrow olleh"` , and

Python example
values[-3:]

safely returns the last three items even if `values` has fewer than three elements.

#slicing#sequences

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semanticsThe Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basics