script_7.py - Nested Lists (Matrix Operations)
Code
See script_7.py for full code.
Explanation
Line 10-14: 2D list (matrix)
- List containing lists (nested structure)
- board is list type
- Each element is also a list (containing strings)
- Represents 3x3 grid
Line 17: for row in board:
- Iterates over outer list
- row is a list (one row of the matrix)
Line 18: print(" | ".join(row))
- .join() is string method
- Takes iterable of strings, joins with separator
- " | " is the separator
- Converts list ["X", "O", "-"] to string "X | O | -"
Line 22: if board[row][col] == "-":
- Double indexing for 2D access
- board[row] gets the row list
- [col] gets element from that row
- Equivalent to: the_row = board[row]; value = the_row[col]
Line 23: board[row][col] = player
- Assignment to nested index
- Modifies element in the 2D structure
- Changes value at specific coordinates
Line 49: diagonal = [matrix[i][i] for i in range(len(matrix))]
- List comprehension accessing diagonal
- i is both row and column index
- Gets matrix[0][], matrix[1][], matrix[2][]
Line 53: transposed = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
- Nested list comprehension
- Outer comprehension creates rows
- Inner comprehension creates columns
- Swaps rows and columns (transpose operation)