Understand Python slicing
Read start, stop, and step correctly, handle negative bounds, and distinguish list slice copies from views and slice assignment.
For built-in lists, tuples, and strings, sequence[start:stop:step] selects elements from start up to, but excluding, stop. The step defaults to one. Omitted bounds depend on the direction of traversal.
Read common slices
items = [0, 1, 2, 3, 4, 5]
print(items[1:4]) # [1, 2, 3]
print(items[2:]) # [2, 3, 4, 5]
print(items[:3]) # [0, 1, 2]
print(items[:]) # [0, 1, 2, 3, 4, 5]
For a list, the full slice is a shallow copy: the outer list is new, but its elements are shared references. Immutable sequences may reuse an existing object for a full slice. Other types, such as NumPy arrays, have their own copy or view behavior.
Change the step
print(items[::2]) # [0, 2, 4]
print(items[1::2]) # [1, 3, 5]
print(items[::-1]) # [5, 4, 3, 2, 1, 0]
print(items[4:1:-1]) # [4, 3, 2]
A zero step raises ValueError. A start greater than the stop produces an empty slice with a positive step, but can select values with a negative step. The direction is essential.
Interpret negative indexes
print(items[-1]) # 5
print(items[-2:]) # [4, 5]
print(items[:-1]) # [0, 1, 2, 3, 4]
A negative explicit bound is interpreted relative to the sequence's length. With a negative step, an omitted stop is not the same as writing -1: items[::-1] reverses the list, while items[:-1:-1] is empty.
| Task | Expression and condition |
|---|---|
| First N items | items[:n], for nonnegative n |
| Last N items | items[-n:], for positive n; handle zero separately |
| Remove both ends from the result | items[1:-1] |
| Copy the outer list | items[:] or items.copy() |
| Take every kth item | items[::k], for positive k |
Slice bounds are clipped rather than raising an out-of-range error. Single-item indexing does not have that behavior.
Assign to a list slice
items = [0, 1, 2, 3]
items[1:3] = [9, 9, 9]
print(items) # [0, 9, 9, 9, 3]
A contiguous slice can be replaced by a different number of values. For an extended slice whose step is not one, the replacement must contain exactly as many values as the slice selects. Strings and tuples do not support item or slice assignment.
FAQ
Why exclude the stop? Adjacent slices fit together: items[:n] + items[n:] reconstructs a list. For normalized in-range bounds with start <= stop and step one, the selected length is stop - start; clipping or another step changes that calculation.
Does a shallow copy isolate nested data? No. A nested list is still shared. Use a deliberate deeper-copy strategy when nested state must be independent.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan