9.1 Modifying and iterating lists
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.
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
.
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
"flash"
comes before
"flask"
.
sort()
function must be applied on the list. The default for the sort()
function is to arrange elements in ascending order.
reverse()
function requires the function to be applied to the list.
"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
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.
my_list
. Line 3 changes the value of the first element in list2
.
9.4 Nested lists
matA
. matA
represents the complete matrix.
matA
is a list [7, 4, 5]
representing the first row of the matrix.
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.
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
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.
for
loop ranges from 0 through 20, stepping by two, but each iterated element is even, so nothing is added to new_list
.