Codectionary / Developer documentation / Python

Slicing

Slicing extracts a sub-portion of a sequence (list, tuple, or string) using the [start:stop:step] syntax. The slice includes the start index but excludes the stop index, similar to range(). All three parts are optional, and negative indices count from the end of the sequence, making slicing a compact way to grab sub-ranges, reverse sequences, or skip elements.

Syntax

sequence[start:stop:step]

Examples

Basic Slicing

Extracting a portion of a list or string by index range.

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(numbers[2:5])   # [2, 3, 4]  (index 5 is excluded)
print(numbers[:4])    # [0, 1, 2, 3]  (from the start)
print(numbers[6:])    # [6, 7, 8, 9]  (to the end)
print(numbers[:])     # a full copy of the list

Negative Indices

Counting from the end of a sequence.

text = "Codectionary"

print(text[-1])     # y (last character)
print(text[-4:])    # nary (last four characters)
print(text[:-4])    # Codectio (everything except the last four)

Step Slicing

Skipping elements using the step parameter.

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(numbers[::2])   # [0, 2, 4, 6, 8]  (every second item)
print(numbers[1::2])  # [1, 3, 5, 7, 9]  (odd indices)

Reversing with Slicing

A common idiom: [::-1] reverses any sequence.

text = "Python"
print(text[::-1])  # nohtyP

numbers = [1, 2, 3, 4, 5]
print(numbers[::-1])  # [5, 4, 3, 2, 1]

Best practices

  • Remember the stop index in a slice is exclusive - sequence[2:5] gives 3 items (indices 2, 3, 4), not 4
  • Use sequence[:] to make a shallow copy of a list, a common and idiomatic pattern
  • Use [::-1] for a quick, readable way to reverse a string, list, or tuple
  • Slicing never raises an IndexError even with out-of-range indices - it just returns as much as is available, unlike direct indexing

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading