COS 100: Introduction to Programming

Interim 2020

Lab 12: List mutation

In this lab, we will write several functions that mutate (change) the given list. A function that acts by mutating its input often has the words "in place" in the specification. Look for those words below.
  1. Write a function increment that takes a list of numbers and increases every number by 1 in place. The function should not return anything (well, it returns None automatically), but rather, mutates the given list.
    numbers = [2, 7., 1, 8]
    increment(numbers)
    print(numbers)
    
    [3, 8.0, 2, 9]
    
  2. Write a function swap that takes a list and two numbers i and j and swaps the ith and jth entry of the list in place.
    yoda = ["mutation", "easy", "is"]
    swap(yoda, 1, 2)
    print(yoda)
    
    ['mutation', 'is', 'easy']
    
  3. Write a function reverse that takes a list and reverses it in place.
    mixed = [2, "word", 3, "tofu"]
    reverse(mixed)
    print(mixed)
    
    ['tofu', 3, 'word', 2]
    
    Make sure your function works for lists of both even and odd lengths.
  4. (Bonus) Write a function sort that takes a list of numbers and sorts it from smallest to largest in place.
    numbers = [2, 7., 1, 8]
    sort(numbers)
    print(numbers)
    
    [1, 2, 7.0, 8]