Python slicing: negative indices and omitted bounds

Read Python slices without guessing: exclusive stop, negative indices and steps, omitted bounds versus -1, out-of-range limits and list copies.

PythonBy
Published on

In short

A slice a[start:stop:step] selects elements starting at start, included, toward stop, excluded, in the direction of step. A negative index counts from the end; a negative step moves backward. With a negative step, an omitted stop lets you reach the first element, whereas an explicit -1 refers to the last element: a[::-1] reverses the list, but a[:-1:-1] is empty.

You may already recognize a[1:3]. The surprises start when you replace a bound with a negative number and then reverse the step. Read these as separate choices: where are the bounds in this list, and which direction are you moving?

Read start, stop and step

The first number is the starting index. The second is the stopping bound, which is never selected. The third is the movement between indices; leave it out and the step is 1.

bounds.py
a = [0, 1, 2, 3, 4, 5]print(a[1:5])print(a[1:5:2])print(a[:3])print(a[3:])
Terminal
$ python3 bounds.py[1, 2, 3, 4][1, 3][0, 1, 2][3, 4, 5]

For a[1:5:2], the visited indices are 1, then 3. The next candidate would be 5, the excluded bound, so selection stops before it. In this particular list the selected values are also 1 and 3. Slice numbers specify positions, rather than values to search for.

  1. 00
  2. 11selected
  3. 22
  4. 33selected
  5. 44
  6. 55excluded bound
a[1:5:2] selects indices 1 and 3

With a positive step, omitting the start begins at the first element. Omitting the stop lets selection reach the last. a[:3] takes the first three elements; a[3:] takes the rest. This split leaves no gap at the joining point.

A negative index does not reverse the direction

For a six-element list, -1 refers to index 5, -2 to index 4, and -3 to index 3. Translate a negative index by adding the length. The step is a separate decision.

negative.py
a = [0, 1, 2, 3, 4, 5]print(a[-3:-1])print(a[4:1:-1])print(a[1:4:-1])print(a[4:0:-2])
Terminal
$ python3 negative.py[3, 4][4, 3, 2][][4, 2]

The first slice moves forward with the implicit step 1, from index 3 to just before index 5. The second moves backward from 4 to just before 1, selecting 4, 3, 2. The third is empty: moving backward from 1 cannot approach the stopping bound 4.

For a[4:0:-2], the visited indices are 4, then 2; 0 is excluded. Stop remains excluded when moving backward. If you need to work through integers generated by a loop, the range bounds guide explains that stopping condition.

Why an omitted stop differs from -1

With a negative step, an omitted start begins at the last element. An omitted stop allows selection through index 0. It does not mean "the index of the last element."

omitted.py
a = [0, 1, 2, 3]print(a[::-1])print(a[:-1:-1])print(a[3:-1:-1])print(a[3::-1])print(a[3:None:-1])
Terminal
$ python3 omitted.py[3, 2, 1, 0][][][3, 2, 1, 0][3, 2, 1, 0]

In a[:-1:-1], the omitted start is index 3 here. The explicit stop -1 also refers to index 3. Selection must stop before that bound, so it cannot select anything. Writing a[3:-1:-1] therefore does not fix it.

To move backward from index 3 and include the first element, write a[3::-1]. A bound set to None has the same meaning as an omitted bound, which explains the matching result from a[3:None:-1].

Out-of-range bounds are adjusted

A single index lookup needs an existing element. A slice can run out of candidates before selecting one and return an empty list. Its bounds are adjusted to the sequence length and direction.

limits.py
a = [0, 1, 2, 3]print(a[-100:100])print(a[100:])print(a[100:-100:-1])print([][::-1])try:    print(a[100])except IndexError as error:    print(type(error).__name__, str(error))try:    print(a[::0])except ValueError as error:    print(type(error).__name__, str(error))
Terminal
$ python3 limits.py[0, 1, 2, 3][][3, 2, 1, 0][]IndexError list index out of rangeValueError slice step cannot be zero

The wide positive slice selects the whole list. With a negative step, the very large start is adjusted to the last element, and the very negative stop allows selection through the first. Reversing an empty list still gives an empty list.

This tolerance can hide a calculation error: getting [] does not prove that your indices are correct. Check what you intended to select. A zero step is forbidden and raises ValueError.

Inspect normalization with slice.indices

When the bounds become hard to read, construct a slice object and call indices with the length. The returned triple can drive a range over the selected indices.

normalized.py
a = [0, 1, 2, 3]selection = slice(None, None, -1)start, stop, step = selection.indices(len(a))print(start, stop, step)print(list(range(start, stop, step)))print([a[i] for i in range(start, stop, step)])print(a[start:stop:step])
Terminal
$ python3 normalized.py3 -1 -1[3, 2, 1, 0][3, 2, 1, 0][]

Here 3, -1, -1 means start at 3, move backward by one, and stop before -1. In this range, -1 is a numeric boundary, rather than a relative list index. The actual indices are 3, 2, 1, 0.

The last line exposes a trap: passing that triple into another slice reinterprets -1 as an index from the end. That slice is empty. Use the triple with range, or keep the original slice object to select from the list. They are not interchangeable representations for reslicing.

Slicing a list creates another list

A list slice leaves its source unchanged. You can also join slices with +.

copy.py
a = [10, 20, 30, 40]b = a[1:3]b[0] = 99print(a)print(b)print(a[-2:] + a[:-2])print(a[-0:])print(a[:-0])
Terminal
$ python3 copy.py[10, 20, 30, 40][99, 30][30, 40, 10, 20][10, 20, 30, 40][]

Replacing a slot in b leaves a unchanged here. This is not a deep copy: if the elements are themselves lists, their references remain shared. The nested list copying guide follows those references in detail. For equality versus a fresh object, see is and ==.

The last two outputs remind you that -0 equals 0. a[-0:] takes the entire list, while a[:-0] takes nothing. Test a computed slice with zero as well as positive counts.

Python

rotate_right

8-bit

Recombine slices to move the last elements to the front. The contract requires a fresh list and unchanged input even for zero movement; also try an empty list and a movement count larger than its length.

Open the exercise

Frequently asked questions

Does slicing work on strings too?

Yes. Built-in strings and tuples follow the same bound rules. A string slice returns a string; a tuple slice returns a tuple. The fresh-list guarantee described here applies to lists. Do not extend it to the identity of an immutable result.

Why is my slice empty?

Check the step sign and the bound positions after translating negative indices. Start must be below stop for a positive step, or above it for a negative step. Equal bounds also give an empty slice.

Is a slice a view into a list?

Not for a built-in Python list: it constructs another list containing the selected references. Replacing a slot in that new list does not replace the original slot, but changing a shared mutable object can be visible through both lists.

Sources

Now write it yourself.