< Back

Activity 27

2-D lists

Two dimensional lists are a very common data structure when dealing with large data. For example, images can be thought of as a two-dimensional list of pixels. They can be a little confusing when using them the first time. Perform the following exercises to solidify your understanding of 2-D lists.


For each of the following, what would the program print if run? Assume that the variable my_matrix is defined as follows

[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
  1. print(my_matrix[2])
    
  2. print(my_matrix[1][0])
    
  3. for element in my_matrix[2]:
        print(element)
    
  4. for i in range(len(my_matrix)):
        print(my_matrix[i][0])
    
  5. for i in range(len(my_matrix)):
        print(my_matrix[i][-i - 1])
    
  6. my_matrix[1].append("j")
    print(my_matrix)  
    
  7. Assume this is executed after the previous sample.

    for row in my_matrix:
       for col in row:
          print(col, end=" ")
       print()