Skip to content

Sequence indexing [ref]

Problem

  • Read the first and last values of [10, 20, 30, 40].
  • Read the second-to-last character of "python".
  • Read row 1, column 2 of [[1, 2, 3], [4, 5, 6]].
  • Replace index 1 of [10, 20, 30] with 99.
  • Read the left and right children of index 2 in a zero-based array heap.

Python solution

nums = [10, 20, 30, 40]
(nums[0], nums[-1])  # (10, 40)

"python"[-2]  # 'o'

matrix = [[1, 2, 3], [4, 5, 6]]
matrix[1][2]  # 6

nums = [10, 20, 30]
nums[1] = 99
nums  # [10, 99, 30]

i = 2
(2 * i + 1, 2 * i + 2)  # (5, 6)