🎓 A1Learner
🔍

Python Nested Lists

A nested list is a list whose items are lists. The inner lists form a grid with rows and columns.

A list of lists

Each inner list is one row of the grid.

grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(grid[0])
print(grid[1])

Pick one cell

Use two indexes. The first picks the row, the second picks the column.

grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(grid[0][0])
print(grid[1][2])
print(grid[2][1])

Loop rows, then cells

The inner loop runs in full for each row.

grid = [[1, 2], [3, 4]]
for row in grid:
    for cell in row:
        print(cell)

Build a grid with loops

Build one row at a time, then add it to the grid.

grid = []
for r in range(3):
    row = []
    for c in range(3):
        row.append(r * 3 + c + 1)
    grid.append(row)
print(grid)

Example

board = [["X", "O", "X"], ["O", "X", "O"], ["-", "-", "X"]]
for row in board:
    print(" | ".join(row))
print(board[0][0], board[1][1], board[2][2])

Key points

  • Nested list: a list whose items are lists
  • Grid: a nested list read as rows and columns
  • Use grid[row][col] to pick one cell, row first, then column
  • Use an outer loop for rows and an inner loop for cells in each row
  • A plain loop is easier to read while you learn.

In this example, board holds three rows of a noughts-and-crosses game. Each row is a list of three marks. The loop prints one row at a time, with join() placing the marks side by side. The last line reads the diagonal from the top left to the bottom right. It picks board[0][0], board[1][1], and board[2][2], and all three are X.

Note

A nested comprehension builds a grid in one line, like [[0 for c in range(3)] for r in range(3)].

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

For grid = [[1, 2], [3, 4]], what is grid[1][0]?