6 of 6
Always remember: grid[row][col] β row first, column second.
grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # β Wrong β this tries column first print(grid[2]) # [7, 8, 9] β this is a row, not a column! # β Correct β row 1, column 2 print(grid[1][2]) # 6
Make sure your indices don't go past the grid size:
grid = [ [1, 2, 3], [4, 5, 6] ] # grid has 2 rows (0-1) and 3 columns (0-2) print(grid[2][0]) # β IndexError! Only rows 0 and 1 exist print(grid[0][3]) # β IndexError! Only columns 0, 1, 2 exist # β Check dimensions first print(len(grid)) # 2 rows print(len(grid[0])) # 3 columns
# β Wrong β all rows point to the SAME list! grid = [[0] * 3] * 3 grid[0][0] = 5 print(grid) # [[5, 0, 0], [5, 0, 0], [5, 0, 0]] β All rows changed! # β Correct β create each row separately grid = [] for r in range(3): grid.append([0] * 3) grid[0][0] = 5 print(grid) # [[5, 0, 0], [0, 0, 0], [0, 0, 0]] β Only row 0 changed
This is a very common Python trap!
When looping through rows, reset your counter/total for each row:
# β Wrong β total keeps growing across all rows total = 0 for row in grid: for num in row: total += num print(total) # Shows cumulative total, not row total! # β Correct β reset total for each row for row in grid: total = 0 # β Reset here! for num in row: total += num print(total) # Shows each row's total
When debugging, print the grid row by row:
def print_grid(grid): for row in grid: print(row) print() # Use it to check your grid at any point print_grid(grid)
| Operation | Code |
|---|---|
| Get element | grid[row][col] |
| Set element | grid[row][col] = value |
| Get a row | grid[row] |
| Number of rows | len(grid) |
| Number of columns | len(grid[0]) |
| Loop by value | for row in grid: for item in row: |
| Loop by index | for r in range(len(grid)): for c in range(len(grid[r])): |
β Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect
β Functions, classes, recursion, print()
β No file system, subprocess, OS access, or network requests
β No pip install (all supported modules are pre-loaded)
β±οΈ 5 second execution time limit