"""Nested lists. Lists within lists; using them to represent matrices http://openbookproject.net/thinkcs/python/english2e/ch09.html#nested-lists """ # A nested list is a list that appears as an element in another list. nested = ["hello", 2.0, 5, [10, 20]] # To extract an element from the nested list, we can proceed in two steps: elem = nested[3] print elem[0] # Or we can combine them: print nested[3][0] # Matrices # Nested lists are often used to represent matrices. For example matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # matrix is a list with three elements, where each element is a row of the matrix. # We can select an entire row from the matrix in the usual way: print matrix[1] # Or we can extract a single element from the matrix using the double-index form: print matrix[1][1] # The first index selects the row, and the second index selects the column. def create_matrix(rows, columns) : """create a matrix with a given number of rows and columns """ matrix = [] for row in range(rows) : matrix += [[0] * columns] return matrix