Skip to content

List construction and mutation [ref]

Problem

  • Append 4 to [1, 2, 3] and remove its last value.
  • Insert "x" at index 1 of ["a", "b"].
  • Extend [1, 2] with [3, 4].
  • Reverse [1, 2, 3] in place.
  • Delete index 1 from [10, 20, 30].
  • Create four zeroes by repeating a one-element list.

Python solution

nums = [1, 2, 3]
nums.append(4)
nums  # [1, 2, 3, 4]
nums.pop()  # 4
nums        # [1, 2, 3]

items = ["a", "b"]
items.insert(1, "x")
items  # ['a', 'x', 'b']

nums = [1, 2]
nums.extend([3, 4])
nums  # [1, 2, 3, 4]

nums = [1, 2, 3]
nums.reverse()
nums  # [3, 2, 1]

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

[0] * 4  # [0, 0, 0, 0]