Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Looping Over Nested Lists

When working with nested lists, looping is essential for processing data effectively. Python provides simple ways to iterate over these structures.

Looping Through a List of Lists

A nested loop is required to access elements within each sublist.

Example: Printing a Nested List

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    print(row)  # Prints each row as a list

Output

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Each row in the loop represents a sublist.

Looping Over Elements in a Nested List

To access individual elements, use a nested loop:

for row in matrix:
    for num in row:
        print(num, end=" ")
    print()  # New line after each row

Output

1 2 3
4 5 6
7 8 9

Using enumerate() to Get Indexes

Sometimes, we need both the row index and the column index.

for row_index, row in enumerate(matrix):
    for col_index, num in enumerate(row):
        print(f"Row {row_index}, Col {col_index} - {num}")

Output

Row 0, Col 0 - 1
Row 0, Col 1 - 2
Row 0, Col 2 - 3
Row 1, Col 0 - 4
...
Row 2, Col 2 - 9

Exercise: Try It Yourself!

  1. Create a nested list representing a 3x3 tic-tac-toe board with "X", "O", and empty spaces " ".
  2. Loop over it and print the board in a readable format.
  3. Modify the board by replacing an empty space with "X" at a chosen position.

Example:

board = [
    ["X", "O", " "],
    [" ", "X", "O"],
    ["O", " ", "X"]
]

# Your loop here