In Python, slicing is a built-in sequence operation that extracts a contiguous or stepped subset of elements from ordered data types—including lists, strings, tuples, and byte arrays—using the syntax sequence[start:stop:step]. Slicing returns a new shallow copy of the selected elements in $O(k)$ time (where $k$ is the slice length) without mutating the original object.


Core Syntax and Mechanics

Python slicing operates on a half-open interval [start, stop), meaning the element at the start index is included, while the element at the stop index is excluded. All three parameters are optional and default to sequence boundaries when omitted.

Parameter Default (Positive Step) Default (Negative Step) Behavior
start 0 (beginning) -1 (end) Inclusive starting index of the slice.
stop len(sequence) (end) Before index 0 Exclusive stopping boundary where traversal halts.
step 1 N/A (must be explicit) Stride or increment between each selected index; cannot be 0.

Standard Indexing and Slicing Patterns

1. Basic Range Extraction

Specifying start and stop isolates a sub-sequence between two positions.

numbers = [10, 20, 30, 40, 50, 60]
language = "Python"

# Extract elements from index 1 up to (but not including) index 4
sub_list = numbers[1:4]      # Output: [20, 30, 40]

# Omit start to slice from the beginning
prefix = language[:2]        # Output: "Py"

# Omit stop to slice through the end
suffix = language[2:]        # Output: "thon"

2. Negative Indexing

Negative indices reference positions relative to the end of the sequence, where -1 denotes the final element.

# Retrieve the last three elements
tail = numbers[-3:]          # Output: [40, 50, 60]

# Exclude the first and last characters of a string
trimmed = language[1:-1]     # Output: "ytho"

3. Stride and Reversal (step)

The step parameter controls the interval between selected items. A negative step reverses the traversal direction.

# Select every second element
alternating = numbers[::2]   # Output: [10, 30, 50]

# Reverse a sequence idiomatically
reversed_str = language[::-1]  # Output: "nohtyP"

Key Behavioral Properties

  • Out-of-Bounds Tolerance: Unlike direct indexing (numbers[99]), which raises an IndexError, slicing automatically clamps indices that exceed sequence boundaries (e.g., numbers[2:100] safely returns [30, 40, 50, 60]).
  • Immutability vs. Mutability: Because strings and tuples are immutable, slicing them always produces a new object. For mutable lists, standard slicing creates a shallow copy (copy_list = numbers[:]), whereas slice assignment (numbers[1:3] = [99, 100]) modifies the list in place.
  • The slice() Built-in Object: Programmatic or reusable slices can be instantiated explicitly using slice(start, stop, step) and passed directly into brackets (e.g., window = slice(0, 3); numbers[window]).