Refer to the Week 10 reading or other resources as necessary to complete this assignment.
At this point, you should be very comfortable using and manipulating one-dimensional lists. Lists usually are created and accessed through loops. For example, this code creates a list of 10 elements, where each element has a value of 0:
my_list = [] # create an empty list for i in range(10): my_list.append(0)
We can also create and initialize a list in a single statement:
list_of_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The elements of a list can be of any data type, including lists. For example:
two_three = [ [1, 2, 3], [10, 11, 13] ]
Here, we have a list with two elements. Each of the elements is itself a list, which makes two_three a two-dimensional list.
Each of the elements of two_three is a row, and each row has three elements (columns).
Copy and paste the following code into the online Python 3 tutor, run it one step at a time, and answer Question 1 in your writeup.
two_three = [ [1, 2, 3], [10, 11, 13] ] for i in range(2): # Two rows for j in range(3): # Three columns print(two_three[i][j], ' ', end='') print()
Using a new browser tab, run the following code in the Python Tutor, and compare it with the previous example. Then answer Question 2 in your writeup.
two_three = [ [1, 2, 3], [10, 11, 13] ] num_rows = len(two_three) for i in range(num_rows): list_i = two_three[i] # The i-th element of two_three num_columns = len(list_i) for j in range(num_columns): print(list_i[j], ' ', end='') print()
Here is yet another code segment that does exactly the same thing. Using a new browser tab, copy and paste it in Python Tutor and run through it one step at a time. Then answer Question 3 in yourwriteup.
def print_list(list_to_print): for i in range(len(list_to_print)): print(list_to_print[i], ' ', end='') print() def print_2d_list(two_d_list): for i in range(len(two_d_list)): print_list(two_d_list[i]) def main(): two_three = [ [1, 2, 3], [10, 11, 13] ] print_2d_list(two_three) main()
Copy and paste the following code into the online Python 3 tutor, run it one step at a time, and answer Question 4 in your writeup.
v = 0 two_d = [] # create an empty list for i in range(5): two_d.append([]) # append an empty list to two_d for j in range(4): two_d[i].append(v) # two_d[i] is the empty list that we just created. # here, we are adding elements to it. v += 1