Skip to content

Python sequence slicing [ref]

Problem

  • Return the first three values, the values from index 2 onward, and the interior values of [0, 1, 2, 3, 4, 5].
  • Reverse [0, 1, 2, 3, 4, 5] with a slice.
  • Select the even-indexed values of [0, 1, 2, 3, 4, 5].
  • Return indices 1 through 3 of "abcde".
  • Replace indices 1 through 3 of [0, 1, 2, 3, 4, 5] with [10, 20].
  • Assign [1, 2, 3] to the even-indexed slots of [0, 0, 0, 0, 0].

Python solution

nums = [0, 1, 2, 3, 4, 5]
nums[:3]    # [0, 1, 2]
nums[2:]    # [2, 3, 4, 5]
nums[1:-1]  # [1, 2, 3, 4]

nums[::-1]  # [5, 4, 3, 2, 1, 0]

nums[::2]  # [0, 2, 4]

"abcde"[1:4]  # 'bcd'; stop index is excluded

nums = [0, 1, 2, 3, 4, 5]
nums[1:4] = [10, 20]
nums  # [0, 10, 20, 4, 5]

nums = [0, 0, 0, 0, 0]
nums[::2] = [1, 2, 3]  # Extended slice requires exactly three replacements.
nums  # [1, 0, 2, 0, 3]