Start free

GCSE · 9 exercises

Python 2d lists

A list of lists is a grid: grid[row][col]. Read one row per line, each turned into numbers.

Loop over rows, then over the columns inside each row. zip(*grid) turns rows into columns.

grid = [[1, 2, 3], [4, 5, 6]]
for row in grid:
    print(*row)
print(grid[1][2])  # 6

Watch for: [[0] * 3] * 2 makes two names for the same row: changing one changes both. Build rows with a comprehension: [[0] * 3 for _ in range(2)].

Exercises

  1. Transpose a matrixSwap the rows and the columns of a matrix.Advanced
  2. Matrix multiplicationMultiply an n by m matrix A by an m by p matrix B.Advanced
  3. Rotate a pictureRotate a grid of characters 90 degrees clockwise.Advanced
  4. Spiral orderPrint the numbers of a matrix in spiral order: along the top row, down the rightAdvanced
  5. Row and column totalsPrint the matrix with the sum of each row added at the end of the row, and a lastAdvanced
  6. Magic squareA magic square has every row, every column and both diagonals adding up to the sameAdvanced
  7. Count the islandsA map shows land (#) and water (.).Advanced
  8. Who won?Look at a finished tic-tac-toe board and say who won: X, O, or draw if nobody hasAdvanced
  9. Minesweeper numbersReplace every empty square (.) of a minesweeper field with the number of mines (*)Advanced
Start with “Transpose a matrix”