Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Slicing: Syntax, Behavior, and Edge Cases

Understand python slicing: start, stop, and step syntax, negative indices, slice assignment, copy semantics, and the edge cases that cause bugs.

~4 min readPython
#python#slicing#sequences#list-slicing
Diagram showing how Python slicing extracts a subrange from a sequence using start, stop, and step indices

Python slicing lets you extract portions of sequences such as lists, strings, and tuples using the sequence[start:stop:step] syntax. Mutable sequences such as lists also use this syntax for slice assignment, which replaces a range with new elements. Slicing appears in almost every Python codebase, yet its details—exclusive stops, negative indices, step direction, and copy semantics—are a common source of subtle bugs.

Basic Slicing Syntax

The simplest form is seq[start:stop], which returns elements from index start up to, but not including, index stop.

python
numbers = [10, 20, 30, 40, 50] print(numbers[1:3]) # [20, 30]

The stop index is exclusive. numbers[1:3] selects elements at positions 1 and 2 only. With the default positive step, if start is omitted, slicing begins at index 0; if stop is omitted, it runs to the end of the sequence.

python
print(numbers[:3]) # [10, 20, 30] print(numbers[2:]) # [30, 40, 50]

Both bounds are optional. For a positive step, the defaults are the beginning and end of the sequence; for a negative step, the defaults are reversed.

Negative Indices

Negative indices count backward from the end of the sequence. Index -1 is the last element, -2 is the second-to-last, and so on.

python
numbers = [10, 20, 30, 40, 50] print(numbers[-2:]) # [40, 50] print(numbers[:-1]) # [10, 20, 30, 40] print(numbers[-3:-1]) # [30, 40]

Combining negative bounds with the default start or stop is a common way to trim trailing or leading elements without computing the sequence length.

The Step Parameter

The full slice syntax is seq[start:stop:step]. The step controls which elements are selected between start and stop.

python
numbers = [10, 20, 30, 40, 50] print(numbers[::2]) # [10, 30, 50] print(numbers[1::2]) # [20, 40]

A negative step traverses the sequence in reverse. seq[::-1] is the idiomatic way to reverse any sliceable sequence.

python
print(numbers[::-1]) # [50, 40, 30, 20, 10]

With a negative step, the default bounds are reversed: omitted start means the end of the sequence, and omitted stop means the beginning. Explicit bounds are still positions in the original sequence; slicing starts at start and moves backward, stopping before stop. For example, numbers[4:1:-1] returns [50, 40, 30], starting at index 4 and moving backward to, but not including, index 1.

A step of zero raises ValueError: slice step cannot be zero.

Slicing Different Sequence Types

Lists, strings, and tuples all support slicing, and each returns a value of the same type.

python
text = "python" print(text[2:5]) # "tho" tuple_data = (1, 2, 3, 4) print(tuple_data[1:3]) # (2, 3)

Slicing a string returns a string, not a list of characters, and slicing a tuple returns a tuple. This type preservation matters when you chain operations: text[2:5].upper() works because text[2:5] is still a string.

Slice Assignment

Lists support slice assignment, which replaces the selected range with the elements of an iterable.

python
numbers = [10, 20, 30, 40, 50] numbers[1:3] = [200, 300] print(numbers) # [10, 200, 300, 40, 50]

For a normal slice with the default step of 1, the replacement iterable does not need to match the slice length. Assigning a shorter list shrinks the list; a longer one grows it.

python
numbers = [10, 20, 30] numbers[1:2] = [100, 110, 120] print(numbers) # [10, 100, 110, 120, 30]

When the slice specifies an explicit step other than 1 (an extended slice), the replacement must have exactly the same length as the slice, because each position is overwritten individually.

python
numbers = [10, 20, 30, 40, 50] numbers[::2] = [0, 0, 0] print(numbers) # [0, 20, 0, 40, 0]

Slice Objects

The slice() built-in creates a reusable slice object that can be passed to any sequence.

python
my_slice = slice(1, 4) numbers = [10, 20, 30, 40, 50] print(numbers[my_slice]) # [20, 30, 40]

Slice objects are useful when the same range must be applied across multiple sequences or stored as a configuration value. They also appear in custom classes that implement __getitem__ to handle slice notation explicitly.

python
reverse_slice = slice(None, None, -1) print(numbers[reverse_slice]) # [50, 40, 30, 20, 10]

Memory and Performance Considerations

Slicing a list creates a new list. This is a shallow copy: the new list holds references to the same objects, not copies of them. The cost is proportional to the slice length, so slicing a list of one million elements creates a new list of one million references.

python
large = list(range(1_000_000)) subset = large[500_000:] # new list with 500,000 references

For strings and tuples, slicing returns a value of the same type. They are immutable, so you should not rely on whether the result is a brand-new object; an implementation may return the original object for a full slice. For a string such as text[2:5] the result is a string, but the useful guarantee is its type, not that it is freshly allocated.

When you need to iterate over a portion of a sequence without materializing a copy, consider itertools.islice for iterators, or iterate over the range directly. For example, for item in large[100:200] builds a 100-element list first; for i in range(100, 200): item = large[i] avoids that allocation. Note that itertools.islice does not support negative start, stop, or step values.

Slice assignment on a list is also O(n) in the worst case because elements after the slice may need to be shifted to accommodate the new length.

Common Mistakes and Edge Cases

Out-of-range indices do not raise an error. Slicing clamps bounds to the sequence length.

python
numbers = [10, 20, 30] print(numbers[5:10]) # [] print(numbers[1:100]) # [20, 30]

A full slice of a list, numbers[:], returns a new list containing references to the same elements. This is a common way to duplicate a list, but it is a shallow copy: nested objects are shared.

python
copy = numbers[:] copy[0] = 99 print(numbers) # unchanged

For nested structures, a shallow copy does not protect inner objects from mutation.

python
matrix = [[1, 2], [3, 4]] copy = matrix[:] copy[0][0] = 99 print(matrix) # [[99, 2], [3, 4]]

When a slice with an explicit step is assigned, a length mismatch raises ValueError: attempt to assign sequence of size X to extended slice of size Y. This is a deliberate guard because the extended slice cannot change length.

python
numbers = [10, 20, 30, 40, 50] numbers[::2] = [0, 0] # ValueError: attempt to assign sequence of size 2 to extended slice of size 3

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.