Exercise: List mutation

In these exercises, you'll practice list mutation using both list methods and bracket notation.

Add to sequence

Implement add_to_sequence, a function that adds a final item to the end of a list that is 1 more than the previous final item of the list.

If you'd like more guidance, expand this block.
  • You should first use bracket notation to access the final item of the list.
  • Then add one to the final item.
  • Finally, use a list method to add that value to the end of the list.
For a code template, expand this block.
last_num = sequence[__]
sequence.______(last_num + 1)
def add_to_sequence(sequence): """ >>> nums = [1, 2, 3] >>> add_to_sequence(nums) >>> nums [1, 2, 3, 4] >>> nums2 = [26, 27] >>> add_to_sequence(nums2) >>> nums2 [26, 27, 28] """

Malcolm in the Middle

Implement malcolm_in_middle, a function that adds a new element with the string 'malcolm' in the middle of the provided list. In the case of a list with odd elements, the string should be inserted to the "right" of the middle. See doctests for examples.

If you'd like more guidance, expand this block.
  • Your solution can be a single line of code.
  • Your code should use a list method to insert the new element.
  • Your code needs to calculate the index based on the current length of the list.
For a code template, expand this block.
sequence.________(___________, 'malcolm')
def malcolm_in_middle(sequence): """ >>> kids = ['jamie', 'dewey', 'reese', 'francis'] >>> malcolm_in_middle(kids) >>> kids ['jamie', 'dewey', 'malcolm', 'reese', 'francis'] >>> kids2 = ['hunter', 'pamela', 'oliver'] >>> malcolm_in_middle(kids2) >>> kids2 ['hunter', 'pamela', 'malcolm', 'oliver'] """

Double time

Implement double_time, a function that doubles each element in the provided list.

Tip: Remember there are several ways to loops through lists. Which way will work better here?

🧩 For more guidance, try a Parsons Puzzle version first.

def double_time(sequence): """ >>> nums = [1, 2, 3] >>> double_time(nums) >>> nums [2, 4, 6] >>> nums2 = [-1, -4] >>> double_time(nums2) >>> nums2 [-2, -8] """
➡️ Next up: More on lists