If you need help reviewing Lists, take a look at these resources:
Each question has a "Toggle Solution" button -- click it to reveal that question's solution.
What would Python print?
Question 1
>>> L = [1, 2, 3, 4]
>>> L[0]
______1
>>> L[100]
______IndexError
>>> L[-1]
______4
>>> L[2] = 100
>>> L
______[1, 2, 100, 4]
Question 2
>>> L = [1, 2, 3, 4]
>>> L[1:3]
______[2, 3]
>>> L[:2]
______[1, 2]
>>> L[1:]
______[2, 3, 4]
>>> L[:]
______[1, 2, 3, 4]
>>> L[0:3:2]
______[1, 3]
>>> L[::-1]
______[4, 3, 2, 1]
Question 3
>>> L = [1, 2, 3, 4]
>>> [1, 2] + [3, 4]
______[1, 2, 3, 4]
>>> [1, 2] * 2
______[1, 2, 1, 2]
>>> L.append(5)
>>> L
______[1, 2, 3, 4, 5]
>>> L.extend([6, 7])
>>> L
______[1, 2, 3, 4, 5, 6, 7]
>>> L.index(5)
______4
>>> L.remove(3)
>>> L
______[1, 2, 4, 5, 6, 7]
>>> L.pop()
______7
>>> L
______[1, 2, 4, 5, 6]
Code-Writing questions
Question 4
Implement a function reverse
that takes a list as an argument and
reverses the list. You should mutate the original list, without
creating any new lists. Do NOT return anything.
def reverse(L):
"""Reverses L in place (i.e. doesn't create new lists).
>>> L = [1, 2, 3, 4]
>>> reverse(L)
>>> L
[4, 3, 2, 1]
"""
"*** YOUR CODE HERE ***"
def reverse(L):
for i in range(len(L)//2):
L[i], L[-i-1] = L[-i-1], L[i]
Question 5
Implement a function map_mut
that takes a list as an argument and
maps a function f
onto each element of the list. You should mutate
the original lists, without creating any new lists. Do NOT return
anything.
def map_mut(f, L):
"""Mutatively maps f onto each element in L.
>>> L = [1, 2, 3, 4]
>>> map_mut(lambda x: x**2, L)
>>> L
[1, 4, 9, 16]
"""
"*** YOUR CODE HERE ***"
def map_mut(f, L):
for i in range(len(L)):
L[i] = f(L[i])