How does list slicing and advanced indexing work in Python?

· Category: Python Programming

Short answer

Python slicing uses the syntax sequence[start:stop:step]. All three parameters are optional. Negative indices count from the end, and a negative step reverses the sequence.

Steps

  1. Use start:stop to extract a subsequence (stop is exclusive).
  2. Use ::step to select every nth item.
  3. Use [::-1] to reverse a sequence.
items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(items[2:5])      # [2, 3, 4]
print(items[:4])       # [0, 1, 2, 3]
print(items[6:])       # [6, 7, 8, 9]
print(items[::2])      # [0, 2, 4, 6, 8]
print(items[::-1])     # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
print(items[-3:])      # [7, 8, 9]

Tips

  • Slicing never raises an IndexError; out-of-bounds indices are clipped gracefully.
  • Assigning to a slice replaces the selected range: items[2:4] = [20, 30].
  • Use itertools.islice for slicing iterators without converting them to lists.
  • slice() objects can be stored and reused: every_third = slice(None, None, 3).

Common issues

  • Forgetting that stop is exclusive leads to off-by-one errors.
  • Using a negative step without specifying start and stop reverses the whole sequence, which is often desired but can be surprising.
  • Modifying a list while iterating over a slice can still cause issues because the underlying list changes.