Discussion 6: Python Lists, Mutability
List Mutation
append
method.
>>> s = [1, 3, 4]
>>> t = s # A second name for the same list
>>> t[0] = 2 # this changes the first element of the list to 2, affecting both s and t
>>> s
[2, 3, 4]
>>> s.append(5) # this adds 5 to the end of the list, affecting both s and t
>>> t
[2, 3, 4, 5]
There are many other list mutation methods:
append(elem)
: Addelem
to the end of the list. ReturnNone
.extend(s)
: Add all elements of iterables
to the end of the list. ReturnNone
.insert(i, elem)
: Insertelem
at indexi
. Ifi
is greater than or equal to the length of the list, thenelem
is inserted at the end. This does not replace any existing elements, but only adds the new elementelem
. ReturnNone
.remove(elem)
: Remove the first occurrence ofelem
in list. ReturnNone
. Errors ifelem
is not in the list.pop(i)
: Remove and return the element at indexi
.pop()
: Remove and return the last element.
Q1: Nested Lists
The mathematical constant e is 2.718281828...
Draw an environment diagram to determine what is printed by the following code.
If you have questions, ask them instead of just looking up the answer! First ask your group, and then the course staff.
Q2: Apply in Place
Implement apply_in_place
, which takes a one-argument function fn
and a list s
. It modifies s
so that each element is the result of applying fn
to that element. It returns None
.
for i in range(...)
to iterate over the indices (positions) of s
.
Immutable Lists
Q3: Reverse (iteratively)
Write a function reverse_iter
that takes a list and returns a new
list that is the reverse of the original. Use iteration! Do not use lst[::-1]
,
lst.reverse()
, or reversed(lst)
!
Tree Recursion with Lists
To solve this problem, all you need are list literals (e.g., [1, 2, 3]
), item selection (e.g., s[0]
), list addition (e.g., [1] + [2, 3]
), len
(e.g., len(s)
), and slicing (e.g., s[1:]
). Use those!
The most important thing to remember about lists is that a non-empty list s
can be split into its first element s[0]
and the rest of the list s[1:]
.
>>> s = [2, 3, 6, 4]
>>> s[0]
2
>>> s[1:]
[3, 6, 4]
Q4: Max Product
Implement max_product
, which takes a list of numbers and returns the maximum product that can be formed by multiplying together non-consecutive elements of the list. Assume that all numbers in the input list are greater than or equal to 1.
max_product
of everything after the first two elements (skipping the second element because it is consecutive with the first), then try skipping the first element and finding the max_product
of the rest. To find which of these options is better, use max
.
Document the Occasion
Please all fill out the attendance form (one submission per person per week).