Unit 11.3A · Term 3

Nested Lists: Creation & Input

A nested list is a list whose elements are themselves lists. In Python, nested lists represent two-dimensional data structures such as tables, matrices, game boards, and grids. Understanding how to create and read them properly from keyboard input is fundamental for data processing.

Learning Objectives

  • 11.2.3.4 Create nested lists in Python
  • 11.2.3.5 Enter elements of nested lists from the keyboard

Lesson Presentation

11.3A-lesson-17-nested-lists-create.pdf · Slides for classroom use

Conceptual Anchor

The Spreadsheet / Grid Model

Think of a nested list as a spreadsheet table or a chessboard. The outer list represents the rows of the table. Each inner list represents the columns within that row. To target a cell, we use two indices: matrix[row][col].

Rules & Theory

Matrix Representation & Indexing

Consider the matrix:

matrix = [ [10, 20, 30], # Row index 0 [40, 50, 60], # Row index 1 [70, 80, 90] # Row index 2 ] print(matrix[0]) # [10, 20, 30] (the entire first row) print(matrix[1][2]) # 60 (Row 1, Column 2) print(matrix[2][0]) # 70 (Row 2, Column 0)

Safe Creation with List Comprehensions

Approach Code Snippet Status & Behavior
List Comprehension (Recommended) [[0] * cols for _ in range(rows)] Safe ✓ Each row is an independent inner list in memory.
Repetition Operator (Dangerous) [[0] * cols] * rows Bug ✗ Copies the reference to one inner list. Modifying one cell modifies the whole column!

Reading a 2D List from Keyboard Input

When input provides $N$ rows, each containing space-separated numbers, standard patterns include:

# Pattern 1: Row-by-row comprehension using map() rows = int(input("Enter number of rows: ")) matrix = [list(map(int, input().split())) for _ in range(rows)] # Pattern 2: Iterative building with append() matrix = [] for i in range(rows): row_data = list(map(int, input().split())) matrix.append(row_data)

Worked Examples

1 Generating an Identity Matrix

An $N \times N$ identity matrix contains 1s on the main diagonal and 0s elsewhere:

n = 4 identity = [[1 if i == j else 0 for j in range(n)] for i in range(n)] for row in identity: print(row) # Output: # [1, 0, 0, 0] # [0, 1, 0, 0] # [0, 0, 1, 0] # [0, 0, 0, 1]

2 Reading Student Grade Sheet from User

Prompt the user for the number of students and their marks across 3 subjects:

num_students = int(input("Number of students: ")) grades = [] for i in range(num_students): # e.g., input: "85 92 78" student_marks = [int(mark) for mark in input(f"Marks for student {i + 1}: ").split()] grades.append(student_marks) # Formatted table output print("\n--- GRADE TABLE ---") print(f"{'Student':<10} {'Math':<6} {'CS':<6} {'Phys':<6}") for idx, marks in enumerate(grades, start=1): print(f"Student {idx:<3} {marks[0]:<6} {marks[1]:<6} {marks[2]:<6}")

3 Formatting 2D Output into a Grid

Print a 2D matrix with aligned columns without bracket notation:

grid = [ [5, 12, 108], [99, 7, 3], [1200, 45, 8] ] for row in grid: for cell in row: print(f"{cell:6d}", end="") print() # Newline after each row

Pitfalls & Common Errors

The Multiplication Pitfall: [[0] * 3] * 3

Never initialize 2D arrays using grid = [[0] * 3] * 3! Doing grid[0][0] = 5 will change the first element of every row: [[5,0,0], [5,0,0], [5,0,0]], because all 3 rows reference the identical object in memory.

Swapping Row and Column Indices

Remember: matrix[i][j] where i is row (vertical position) and j is column (horizontal position). Inverting them leads to IndexError when rows and columns differ in length.

Pro-Tips for Exams

Exam Checklist

  • Dimensions of a matrix: rows = len(matrix), columns = len(matrix[0]).
  • To read an $N \times M$ matrix in one clean line during exam tasks:
    matrix = [list(map(int, input().split())) for _ in range(n)]
  • Main diagonal condition: row_idx == col_idx.

Graded Tasks

Remember

Write Python syntax to access the element at row 2, column 3 of a nested list called data.

Understand

Draw memory diagrams illustrating why [[0]*2 for _ in range(2)] behaves differently from [[0]*2]*2.

Apply

Write a program that takes $N$ and $M$ as input, reads an $N \times M$ matrix from the keyboard, and prints each row on a separate line.

Analyze

Given arr = [[1, 2], [3, 4], [5, 6]], determine what len(arr) and len(arr[1]) evaluate to.

Create

Create a 3x3 Tic-Tac-Toe board initializer: ask two players to take turns inputting coordinates (row, col) and update the board with "X" and "O".

Self-Check Quiz

1. In a = [[1, 2, 3], [4, 5, 6]], what does a[1][0] evaluate to?
Click to reveal answer
2. How many rows and columns does [[0] * 5 for _ in range(3)] have?
Click to reveal answer
3. What is the standard idiom to read an integer row from user input?
Click to reveal answer
4. What error occurs if you call grid[5][0] on a 3-row grid?
Click to reveal answer
5. What does len(matrix) return for a 2D list?
Click to reveal answer