← Back to Python, page 2

python-0022 · Easy fresher

How does slicing work on lists and strings, including negative steps?

seq[start:stop:step] returns a new sequence from start up to but not including stop, moving by step. Omitted bounds default to the ends, negative indexes count from the end, and a negative step walks backwards, so s[::-1] reverses. Slices never raise IndexError for out-of-range bounds.

Full answer
python
s = "PYTHON"
print(s[1:4], s[:2], s[-2:], s[::2], s[::-1])
nums = [0, 1, 2, 3, 4, 5]
print(nums[4:1:-1], nums[10:], nums[-100:2])
copy = nums[:]
copy[0] = 99
print(nums[0], copy[0])
nums[1:3] = ["a", "b", "c"]
print(nums)

Output:

text
YTH PY ON PTO NOHTYP
[4, 3, 2] [] [0, 1]
0 99
[0, 'a', 'b', 'c', 3, 4, 5]

s[1:4] gives 'YTH' because the stop index is excluded. s[::-1] reverses the string, and nums[4:1:-1] walks backwards from index 4 down to, but not including, index 1. Out-of-range bounds such as nums[10:] simply give an empty list. nums[:] makes a shallow copy, and assigning to a slice can replace a section with a different number of items, growing the list.

python
s = "PYTHON"
print(s[1:4], s[:2], s[-2:], s[::2], s[::-1])
nums = [0, 1, 2, 3, 4, 5]
print(nums[4:1:-1], nums[10:], nums[-100:2])
copy = nums[:]
copy[0] = 99
print(nums[0], copy[0])
nums[1:3] = ["a", "b", "c"]
print(nums)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • stop is exclusive
  • Negative indexes count from the end
  • Negative step reverses direction
  • Out-of-range slices do not raise
  • Slice assignment can resize lists

Common mistakes

  • Expecting the stop index to be included
  • Expecting IndexError from slices

Follow-ups

  • How does slice() as an object work?
  • Is s[::-1] the best way to reverse a list in place?

Tips

  • Count positions between characters