Complete the following problems on paper. Try to solve each problem on paper first before using Thonny to confirm your answers.
[PP Problem 8.4] The value of the variable ids
is the list [4353, 2314,
2956, 3382, 9362, 3900]
. Using list
methods,
do the following:
a. Remove 3382 from the list.
b. Get the index of 9362.
c. Insert 4499 in the list after 9362.
d. Extend the list by adding [5566, 1830] to it.
e. Reverse the list.
f. Sort the list.
Since strings and lists are both sequences, many Python expressions can be
applied to both string values and list values. For each of the expressions
below, determine whether the expressions is valid if value
is both a
string and a list, only for a string, only for a list or if it depends.
value + value
[value]
len(value)
value[:4]
"abc" + value
What is the value of x
after this code executes?
x = []
for i in range(3):
x.insert(0, len(x))
Write docstrings for the following functions describing what each of them do:
Mystery Function 1
def mystery1(num1, num2):
result = []
for i in range(num1):
result.append(num2)
return result
Mystery Function 2
def mystery2(num1, num2):
return [num2]*num1
Mystery Function 3
def mystery3(a_list):
for i in range(len(a_list) // 2):
other_index = len(a_list)-i-1
temp = a_list[i]
a_list[i] = a_list[other_index]
a_list[other_index] = temp
[PP Problem 8.7] Write a function named same_first_last
that takes a list
as a parameter and returns True
if and only if the first and last element
of the list are equal. You can assume that the list has at least one
element.
[PP Section 8.8] You are experimenting with the following code to provide a
list of colors in sorted order, but you are getting an error when your for
loop executes. What is the problem and how would you fix it?
colors = 'red orange yellow green blue purple'.split()
sorted_colors = colors.sort()
for color in sorted_colors:
print(color)
I typically teach two classes a semester. At the beginning of the semester I
want to find out how many students are enrolled in both classes. Assume that
I have two files containing the respective class rosters. Write a function
named common_students
that takes the two files as arguments and returns
the number of students enrolled in both courses. Recall that you can use the
in
operator to test if a value is present in a list.