Slicing sequences

Python · Practical · 7 min

Slicing is the idiomatic way to take parts of sequences without index arithmetic loops.

A slice seq[start:stop:step] selects a range of a list, tuple, string or any sequence. It includes start and excludes stop, just like range. Every part is optional:

  • s[:3] the first three items, s[3:] everything from index 3
  • s[-2:] the last two, s[:-1] all but the last
  • s[::2] every second item, s[::-1] the sequence reversed
  • s[:] a shallow copy of the whole thing

Slices are forgiving: unlike indexing, out-of-range bounds are clipped rather than raising, so "abc"[1:100] is just "bc" and [][:5] is []. That makes "the first n items" safe on short inputs.

A slice always returns a new object of the same type (for built-in sequences). For lists that means a copy of the references — modifying the slice doesn't change the original.

On mutable sequences you can also assign to a slice, which replaces that range with the items of an iterable, even of a different length: nums[1:3] = [7, 8, 9]. del nums[::2] deletes every second item. Extended slices with a step require the replacement to have exactly the same length.

When the same slice is used in several places, name it: HEADER = slice(0, 4) then record[HEADER]. The slice object is exactly what the colon syntax creates under the hood, and your own classes receive it in __getitem__.

For very large data, remember each slice copies; NumPy arrays and memoryview slices are views instead.

Example

letters = "abcdefgh"
print(letters[2:5])      # cde
print(letters[:3], letters[-3:])   # abc fgh
print(letters[::2])      # aceg
print(letters[::-1])     # hgfedcba
print(letters[5:100])    # fgh  (bounds are clipped)

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

nums[1:3] = [7, 8, 9]    # replace 2 items with 3
print(nums)              # [0, 7, 8, 9, 3, 4, 5]
del nums[::2]
print(nums)              # [7, 9, 4]

YEAR = slice(0, 4)
print("2026-10-16"[YEAR])   # 2026

Remember

  • s[start:stop:step] includes start, excludes stop
  • Slices clip out-of-range bounds instead of raising
  • s[::-1] reverses, s[:] shallow-copies

Watch out for

  • Assuming a list slice is a view; changes to it don't affect the original.

Check yourself

  1. What is `[10, 20, 30, 40, 50][-4:-1]`?
  2. What does `"python"[10:]` return?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/stdtypes.html#common-sequence-operations