9.1 Modifying and iterating lists
2.
c.
The element to be removed is passed as a parameter to the remove operation. The remove is performed on the specified list.
3.
c.
Both
pop()
and remove()
can be used to remove the last element of a list. pop()
automatically removes the last element, whereas remove()
requires the last element be specified.
5.
b.
len(my_list)
is 5. A counting
for
loop ends at 1 less than the second value in the range function, so the final value of i
is
4
.
6.
a.
The
for
loop steps by two each time, so index 0, 2, and 4 are printed. Due to the
"end="
in the print statement, all elements are printed on one line.
9.2 Sorting and reversing lists
1.
b.
Sorting in descending order means to arrange the elements from largest to smallest. -3 is the smallest element of the list and would be the last element when the list is sorted in descending order.
3.
c.
In alphabetical order, "h" comes before "k". The first four characters are the same, so
"flash"
comes before
"flask"
.
4.
b.
The
sort()
function must be applied on the list. The default for the sort()
function is to arrange elements in ascending order.
5.
a.
The correct syntax for the
reverse()
function requires the function to be applied to the list.
6.
a.
"go"
is the first element of board_games
, so
"go"
would be the last element once board_games
is reversed.
9.3 Common list operations
4.
c.
list2
refers to the same list as my_list
, so any changes made to list2
also reflect on my_list
. 18 is the summation of the values in the list.
5.
a.
3 is the maximum value in the list
my_list
. Line 3 changes the value of the first element in list2
.
9.4 Nested lists
1.
a.
Each row of the matrix is represented as a list in the larger list-of-lists,
matA
. matA
represents the complete matrix.
2.
c.
6 is in the 2nd row and 3rd column. Using zero-indexing results in index 1 for the row and 2 for the column.
3.
c.
The first element of the list
matA
is a list [7, 4, 5]
representing the first row of the matrix.
4.
a.
The outer
for
loop iterates row by row. The inner
for
loop iterates through each element in a row. So all the numbers are printed, starting from 7 and ending in -5.
5.
c.
The outer
for
loop runs for three iterations because there are three elements in the list-of-lists. The inner
for
loop iterates through each element of each row using the length of each row.
9.5 List comprehensions
3.
b.
The
for
loop starts at 1 and steps by three, so it begins at 1 and ends at 13. Dividing using the //
operator results in dropping the part after the decimal.
6.
a.
The
for
loop ranges from 0 through 20, stepping by two, but each iterated element is even, so nothing is added to new_list
.