Browse topics

Sequence slicing

Version
3.14
Review
Draft

Summary#

A slice selects part of a sequence from a start index up to, but excluding, a stop index. An optional step skips items or walks backward. Assigning to a list slice replaces that range.

Syntax#

python
sequence[start:stop]
sequence[start:stop:step]
items[start:stop] = replacement
named = slice(start, stop, step)

Example#

python
letters = ["a", "b", "c", "d", "e", "f"]

print(letters[1:4])
print(letters[-2:])
print(letters[::2])
print(letters[::-1])
print(letters[10:20])

changed = letters[:]
changed[1:4] = ["X"]
print(changed)
print(len(letters))
print("abcdef"[slice(-3, None)])

Expected output#

Text
['b', 'c', 'd']
['e', 'f']
['a', 'c', 'e']
['f', 'e', 'd', 'c', 'b', 'a']
[]
['a', 'X', 'e', 'f']
6
def

Common mistakes#

items[-n:] returns the whole sequence when n is zero because -0 equals 0. Use items[len(items) - n:] when n ranges from zero to the length. A list slice is a shallow copy, so nested objects remain shared. With a step other than 1, list slice assignment requires exactly as many replacement items as selected positions.

Version applicability#

The slicing and assignment forms shown work on all Python 3 releases. Slice objects became hashable in Python 3.12 when their start, stop and step are hashable.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0