COS 100: Introduction to Programming
Interim 2022
Lab 11: 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.-
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 returnsNone
automatically), but rather, mutates the given list.For example, after you are done writing the function
increment
, the following codenumbers = [2, 7., 1, 8] increment(numbers) print(numbers)
should print[3, 8.0, 2, 9]
-
Write a function
swap
that takes a list and two numbersi
andj
and swaps thei
th andj
th entry of the list in place.yoda = ["mutation", "easy", "is", "!"] swap(yoda, 1, 2) print(yoda)
['mutation', 'is', 'easy', '!']
-
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. - (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]