← Back to Nested Lists
πŸ’‘

Tips & Common Mistakes

6 of 6

Nested Lists β€” Tips & Common Mistakes

Common Mistake 1: Wrong Index Order

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

Common Mistake 2: Index Out of Range

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

Common Mistake 3: Creating Grids the Wrong Way

# ❌ 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!


Common Mistake 4: Forgetting to Reset Variables

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

Debugging Tip: Print the Grid Nicely

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)

Quick Reference

OperationCode
Get elementgrid[row][col]
Set elementgrid[row][col] = value
Get a rowgrid[row]
Number of rowslen(grid)
Number of columnslen(grid[0])
Loop by valuefor row in grid: for item in row:
Loop by indexfor r in range(len(grid)): for c in range(len(grid[r])):

When to Use Nested Lists

  • Game boards β€” tic-tac-toe, chess, minesweeper
  • Maps/grids β€” Roblox terrain, mazes
  • Tables of data β€” scores, schedules
  • Images β€” pixel grids, color maps
  • Math β€” matrices, coordinate systems
πŸ’»

Try it yourself

Code: Tips & Common Mistakes

Loading Python runtime…
Python …
Loading...
Output
Click "Run" to execute your code...
ℹ️ About this Python environment

βœ… 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