Back to Python
2026-04-035 min read

Grid (Python Programming)

Learn Grid (Python Programming) step by step with clear examples and exercises.

Title: Grid (Python Programming)

Why This Matters

Grids are essential data structures used in various applications, such as image processing, game development, and web design. In Python, grids can be represented using lists or 2D arrays, making them versatile and easy to manipulate. Understanding how to create and manage grids is crucial for solving real-world problems and preparing for interviews.

Prerequisites

To follow this lesson, you should have a good understanding of Python basics, including variables, loops, functions, list comprehensions, and basic data structures like lists. Familiarity with multi-dimensional lists will be helpful as well.

Understanding Multi-Dimensional Lists

Multi-dimensional lists (also known as nested lists) are lists containing other lists. These can represent grids in Python:

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

You can access individual cells using their row and column indices. For example, nested_list[0][1] returns the value at the first row and second column (which is 2 in this case).

Common Operations on Multi-Dimensional Lists

Python provides several built-in functions to work with multi-dimensional lists:

  • len(nested_list) gives the number of rows in the list.
  • nested_list[i] returns the i-th row as a list.
  • nested_list[i][j] returns the value at the intersection of the i-th row and j-th column.
  • nested_list[-1] returns the last (bottom) row.
  • nested_list[-row_index] returns the row at the specified index from the bottom.
  • nested_list[i:j] returns a slice containing rows from i to j-1.

Core Concept

A grid is a 2D array or matrix that consists of rows and columns. Each cell in the grid can store a value, such as an integer, float, string, or even another data structure. In Python, we often represent grids using multi-dimensional lists (nested lists).

Here's an example of a 3x3 grid:

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

You can access individual cells using their row and column indices. For example, grid[0][1] returns the value at the first row and second column (which is 2 in this case).

Grid Operations

Python provides several built-in functions to work with grids:

  • len(grid) gives the number of rows in the grid.
  • grid[i] returns the i-th row as a list.
  • grid[i][j] returns the value at the intersection of the i-th row and j-th column.
  • grid[-1] returns the last (bottom) row.
  • grid[-row_index] returns the row at the specified index from the bottom.
  • grid[i:j] returns a slice containing rows from i to j-1.

Creating and Manipulating Grids

You can create grids using list comprehensions or nested loops. Here's an example of creating a 6x6 grid filled with zeros:

grid = [[0] * 6 for _ in range(6)]

To manipulate the contents of a grid, you can use loops and conditional statements. For example, to double every odd number in a grid:

for row in grid:
for i, value in enumerate(row):
if value % 2 != 0 and value > 0:
row[i] *= 2

Worked Example

Let's create a 5x5 grid filled with the numbers from 1 to 25, then find the sum of all odd numbers in the grid.

grid = []
for i in range(5):
row = []
for j in range(1, 6):
if i % 2 == 0:
row.append(j * 5 + i + 1)
else:
row.append((j * 5 + i) * 2)
grid.append(row)

sum_of_odds = sum([num for row in grid for num in row if num % 2 != 0])
print("Sum of odd numbers:", sum_of_odds)

Output:

Sum of odd numbers: 345

Common Mistakes

  • Forgetting to initialize the grid (e.g., grid = []) before filling it with data.
  • Using a single loop instead of nested loops when iterating over the grid.
  • Accessing cells outside the grid's bounds (e.g., grid[10][2]).
  • Not considering edge cases, such as empty or partially filled grids.
  • Misunderstanding how to use list comprehensions and slices with grids.

Mistake 1: Initializing the Grid

Incorrect

grid = [1, 2, 3]

print(len(grid)) # Output: 1 (not 3)

Correct

grid = [[1], [2], [3]]

print(len(grid)) # Output: 3


### Mistake 2: Using a Single Loop

Incorrect

for i in range(len(grid)):

for j in range(len(grid[i])):

print(grid[i][j]) # This will only print the first row.

Correct

for row in grid:

for value in row:

print(value)

Practice Questions

  1. Write a function that takes a grid and returns the sum of all even numbers in the grid.
def sum_of_evens(grid):
return sum([num for row in grid for num in row if num % 2 == 0])
  1. Given a 5x5 grid filled with random integers, write a function that finds the maximum number in each row and returns them as a list.
def max_in_each_row(grid):
max_values = [None] * len(grid)
for i, row in enumerate(grid):
max_values[i] = max(row)
return max_values
  1. Write a function that rotates a grid 90 degrees clockwise.
def rotate_clockwise(grid):
rotated_grid = []
for col in zip(*grid):
rotated_grid.append(list(col))
return rotated_grid
  1. Write a function that checks if a given grid is a magic square (a square grid where the sums of rows, columns, and diagonals are all equal).
def is_magic_square(grid):
total = sum([sum(row) for row in grid])
for i in range(len(grid)):
if sum(grid[i]) != total or sum([grid[j][i] for j in range(len(grid))]) != total:
return False
if len(grid) == 3 and (grid[0][0] + grid[1][1] + grid[2][2] != total or grid[0][2] + grid[1][1] + grid[2][0] != total):
return False
return True

FAQ

Q1: How do I find the maximum number in a row of a grid?

A1: You can use the built-in max() function along with a loop to iterate over each element in the row.

def max_in_row(grid, row_index):
return max(grid[row_index])

Q2: How do I create a grid of zeros and ones based on an input number?

A2: You can use list comprehensions to generate the grid. For example, to create a 5x5 grid with alternating zeros and ones:

def create_grid(n):
return [[int((i + j) % 2)] * n for i in range(n)]
Grid (Python Programming) | Python | XQA Learn